Home > Mobile >  Do I need to mention the coroutine dispatcher while working with Retrofit and Room?
Do I need to mention the coroutine dispatcher while working with Retrofit and Room?

Time:05-04

Recently I saw this - Most data sources already provide main-safe APIs like the suspend method calls provided by Room or Retrofit. Your repository can take advantage of these APIs when they are available.

What does this mean? Is the dispatcher under the hood Dispatcher.IO for Retrofit and Room? Or do I need to mention that explicitly, while making the request?

withContext(Dispatchers.IO) {
    // Some retrofit call or room query
}

CodePudding user response:

No you don't need to mention dispatchers for Retrofit and Room. For Room when you mark a dao function as suspend fun it is guaranteed that it will not block main thread.

You can read this article https://medium.com/androiddevelopers/room-coroutines-422b786dc4c5

from the article

Room calls the CoroutinesRoom.execute suspend function, which switches to a background dispatcher, depending on whether the database is opened and we are in a transaction or not.

CodePudding user response:

No, you don't need to switch context when calling suspend functions of Retrofit and Room. I'm not sure if they use Dispatcher.IO under the hood, maybe they use their custom context composed of thread pools, but it is guaranteed to be called in background thread.

For example you can call suspend Dao functions in ViewModel class like the following:

viewModelScope.launch {
    val user dao.getCurrentUser()
    // Update UI using user
}

assuming getCurrentUser() is a suspend function:

suspend fun getCurrentUser(): User
  • Related