Search code examples
androidkotlinkotlin-coroutinesandroid-viewmodelandroid-mvvm

Which is better to use for API calls, Dispatcher.IO or Dispatcher.Main?


I am using an MVVM architecture pattern 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 executed in an IO thread or just use the Dispatcher provided by the ViewModel, which is Dispatcher.Main?


Solution

  • 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() { ... }