'Do I need to mention the coroutine dispatcher while working with Retrofit and Room?

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? Thank you.

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


Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yunus Dilber
Solution 2 BigSt