启动协程时出现“无法访问主线程上的数据库,因为它可能会长时间锁定 UI”错误

Ale*_*now 2 android kotlin android-mvvm android-room kotlin-coroutines

我收到此错误:无法访问主线程上的数据库,因为它可能会长时间锁定 UI。当我在 ViewModel 中启动有趣的turnAllWordsOn() 时,就会发生这种情况(代码如下)。这个函数启动协程,我认为协程总是在后台线程上工作。那么为什么我会收到此错误?感谢任何帮助

在片段中:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        R.id.action_turn_all_words_on -> {
            viewModel.turnAllWordsOn()
            true
        }
    // othes items
    }
Run Code Online (Sandbox Code Playgroud)

在视图模型中:

fun turnAllWordsOn() = viewModelScope.launch {
    wordDao.turnAllWordsOn()
}
Run Code Online (Sandbox Code Playgroud)

在道中:

@Query("UPDATE word_table SET shown = 1")
fun turnAllWordsOn()
Run Code Online (Sandbox Code Playgroud)

Hen*_*ist 6

如果您希望 Room 在后台线程上运行 Dao 函数,则必须将其标记为挂起函数。否则,您所做的就是从协程范围调用同步函数。

@Query("UPDATE word_table SET shown = 1")
suspend fun turnAllWordsOn()
Run Code Online (Sandbox Code Playgroud)

附带说明一下,挂起函数不会自动在后台线程上运行,但是当您将查询标记为挂起时,Room 会在幕后执行必要的工作。