What is the correct way to use Android Room with Kotlin Coroutines?

Viewed 2866

While learning how to use Kotlin Coroutines recently, have been read several relevant articles. But one of them confuse me: Coroutines On Android (part III): Real work

As it pointed out:

Note: Room uses its own dispatcher to run queries on a background thread. Your code should not use withContext(Dispatchers.IO) to call suspending room queries. It will complicate the code and make your queries run slower.

It seems to make sense at the time I saw these paragraph, but when I open an Android project and trying to dive into, the problem shows up, Android Studio warns me:

suspend function 'yourMethod' should be called only from a coroutine or another suspend function

I'm now freezing here, because the article told me not to use withContext(Dispatchers.IO). And I am now wondering should I use withContext(Dispatchers.Main) or use GlobalScope.launch to run my queries?

1 Answers

you should use Dispatchers.IO on your repository, in your viewModel you can use viewModelScope.

Related