Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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() { ... }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading