Home > Back-end >  Which is better to use for API calls Dispatcher.IO or Dispatcher.Main?
Which is better to use for API calls Dispatcher.IO or Dispatcher.Main?

Time:09-28

Hei, I am using a MVVM archetectural patern in my android application. I wanted to have api calls from my Viewmodel using coroutinescope.lauch{} Do I need to specify the Dispatcher as Dispatcher.IO as it will be exicuted in a IO thread or just use the Dispathcer provided by the viewmodel which is Dispatcher.Main

CodePudding user response:

There is an extension property on ViewModel class, called viewModelScope which works on Dispatcher.Main context by default. You can use it to call your api functions if they are suspend, e.g.:

viewModelScope.launch {
    apiFunction()
    // do other stuff
}

suspend fun apiFunction() { ... }

It is OK to call suspend functions on Dispatchers.Main context, they will suspend a coroutine but not block the Main Thread.


If your API functions are not suspend you can convert them to suspend functions by switching context to Dispatchers.IO using withContext() function. Or if API functions use callbacks you can consider using suspendCoroutine or suspendCancellableCoroutine. Example of using withContext:

viewModelScope.launch {
    apiSuspendFunction()
    // do other stuff
}

suspend fun apiSuspendFunction() = withContext(Dispatchers.IO) { 
    apiNonSuspendFunction()
}

fun apiNonSuspendFunction() { ... }

CodePudding user response:

For api call Dispatcher.IO is better

for more info

https://proandroiddev.com/kotlin-coroutines-in-android-summary-1ed3048f11c3

https://miro.medium.com/max/720/1*K-5ZG6rVR5Dl9J5E3Rx7eA.png

And in your case you use mvvm so more better to use ViewModelScope

    viewModelScope.launch { 
        // operation
    }
  • Related