Question: I read that Android's Room uses its own ...
# android
s
Question: I read that Android's Room uses its own Dispatcher to run all query functions. 1. Is that true? and 2. If so, what is the correct way to run suspend fun queries from the view model? What dispatcher should I launch the coroutine with which runs the query?
g
just run them, no need to worry about particular dispatcher, because it will run the query on own thread pool and return result to your own dispatcher, so use any dispatcher which is required for your code, not for room, usually just use default dispatcher of CoroutineScope
s
ah, gotcha! thanks!
g
in general, correct implementation of any suspend function should never require any specific dispatcher and never should be blocking, everything else should be considered as bug of implementation of this suspend function
s
Getting this error when trying to just launch it without a specific dispatcher from my ViewModel's scope :
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
😞
Well, I am 98.9% sure it's because my ViewModel's context is
viewModelScope.coroutineContext
which is bound to
Dispatchers.Main
But now I'm not entirely sure of the correct way to handle this
g
is it happening when you launch suspend function from room?
or blocking one?
s
when I call
Copy code
viewModel.launch { 
    val destination = destinationsDao.getLastActive(true)
}
from my fragment. the query is:
Copy code
@Query("SELECT * FROM destinations WHERE last_active = :lastActive")
    fun getLastActive(lastActive: Boolean) : Destination?
d'oh, i had removed my suspend from my query function, popping that back in fixed it
g
But this is not a suspend function
yes, exactly