Search code examples
androidkotlinandroid-roomandroid-viewmodel

How to get static data in Room? Cannot access database on the main thread


I have to get some data from my DB which then will be casted to json, i have made two methods in my DAOs which returns the items i need like the following:

TestataDAO:

@Query("SELECT * FROM testata WHERE id = :id")
fun selectTestata(id: Int): Testata

Then in my repository i set this:

@WorkerThread
fun selectTestata(idTestata: Int): Testata {
    return testataDAO.selectTestata(idTestata)
}

And in my viewModel like this:

fun selectTestata(idTestata: Int): Testata {
    return repository.selectTestata(idTestata)
}

The issue is that if i try to get that value i get the following error:

Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

So at this point i have to set my function as suspended in Repository and make it like coroutine in the ViewModel, but how can i return Testata from the coroutine?

Here is how it should be:

Repository:

@WorkerThread
suspend fun selectTestata(idTestata: Int): Testata {
    return testataDAO.selectTestata(idTestata)
}

ViewModel:

fun selectTestata(idTestata: Int): Testata = viewModelScope.launch{
    return repository.selectTestata(idTestata)
}

But here i get the error as i can't return Testata by using .launch...

How can i solve it?


Solution

  • You could use it like below, call this method with in coroutine scope:

    suspend fun selectTestata(idTestata: Int): Testata  = withContext(Dispatchers.IO){
        repository.selectTestata(idTestata)
    }