【发布时间】:2021-03-09 07:47:56
【问题描述】:
我必须从我的数据库中获取一些数据,然后将其转换为 json,我在我的 DAO 中创建了两个方法,它们返回我需要的项目,如下所示:
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)
}
问题是,如果我尝试获取该值,我会收到以下错误:
无法访问主线程上的数据库,因为它可能潜在地 长时间锁定 UI。
所以此时我必须将我的函数设置为在 Repository 中暂停,并使其像 ViewModel 中的协程一样,但是我如何从协程返回 Testata?
应该是这样的:
存储库:
@WorkerThread
suspend fun selectTestata(idTestata: Int): Testata {
return testataDAO.selectTestata(idTestata)
}
视图模型:
fun selectTestata(idTestata: Int): Testata = viewModelScope.launch{
return repository.selectTestata(idTestata)
}
但在这里我得到了错误,因为我无法使用 .launch 返回 Testata...
我该如何解决?
【问题讨论】:
标签: android kotlin android-room android-viewmodel