https://kotlinlang.org logo
#android
Title
# android
s

Shan

07/01/2019, 2:45 AM
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

gildor

07/01/2019, 3:11 AM
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

Shan

07/01/2019, 3:12 AM
ah, gotcha! thanks!
g

gildor

07/01/2019, 3:15 AM
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

Shan

07/01/2019, 3:21 AM
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

gildor

07/01/2019, 3:41 AM
is it happening when you launch suspend function from room?
or blocking one?
s

Shan

07/01/2019, 3:43 AM
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

gildor

07/01/2019, 3:46 AM
But this is not a suspend function
yes, exactly
2 Views