如何获取 Room 中的静态数据?无法在主线程上访问数据库

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

我必须从我的数据库中获取一些数据,然后将其转换为 json,我在我的 DAO 中创建了两个方法,其中 return 是我需要的项目,如下所示:

TestataDAO:

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

然后在我的存储库中我设置了这个:

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

在我的 viewModel 中是这样的:

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

问题是,如果我尝试获取该值,则会出现以下错误:

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

所以此时我必须将我的函数设置为在存储库中暂停并使其像 ViewModel 中的协程一样,但是我如何 return Testata 来自协程?

应该是这样的:

存储库:

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

视图模型:

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

但是这里我得到了错误,因为我无法使用 .launch return Testata...

我该如何解决?

您可以像下面这样使用它,在协程范围内调用此方法:

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