[FIXED] Which is better to use for API calls Dispatcher.IO or Dispatcher.Main?


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


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 {
    // 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 {
    // do other stuff

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

fun apiNonSuspendFunction() { ... }

Answered By – Sergio

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published