I am doing my best to do database room stuff in co...
# android
m
I am doing my best to do database room stuff in coroutines, but my project crashes every time. It thinks I'm touching database in the main thread. I swear I'm not!
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
I'm doing all insertions in coroutine contexts like:
Copy code
fun removeMessage(message: Message) = viewModelScope.launch{
    repository.remove(message)
}
j
Have you tried to pass the context Dispatchers.IO in the launch?
k
Did you set your
dao
function to be suspendable?
1
solved 1
a
Viewmodelscope runs on. Main dispatcher
2
You'll need to change context
m
@K Merle you nailed it. I was not using suspend keyword for Dao functions 😅🙈
🙌 1
@joadar where should I pass Dispatchers.IO? To CoroutineContext()?
a
The launch methods constructor can take in a dispatcher. Like
launch(<http://Dispatchers.IO|Dispatchers.IO>) { // code }
. You should inject your dispatchers tho.
3
a
If your dao functions are declared suspend then you do not need to manually change contexts. Of the two approaches, prefer declaring your dao functions as suspend functions.
❤️ 3
a
Why because room will generate the necessary context on implementation?
a
it will keep its blocking I/O work off of the calling thread on its own, yes.
👍 1
❤️ 1