【问题标题】:suspend method inside runInTransaction blockrunInTransaction 块内的挂起方法
【发布时间】:2020-12-19 22:52:37
【问题描述】:

我使用以下代码时出现编译错误:

只能在协程体内调用挂起函数

谁能给我解释一下为什么?我需要做什么才能使其工作(不使用@Transaction 注释)?

override suspend fun replaceAccounts(newAccounts: List<Account>) {
    database.runInTransaction {
        database.accountDao().deleteAllAccounts() // I have the error on this line
        database.accountDao().insertAccounts(newAccounts) // Here too
    }
}

@Dao
abstract class AccountDao : BaseDao<AccountEntity> {

    @Query("DELETE FROM Account")
    abstract suspend fun deleteAllAccounts()

}

提前感谢您的帮助

【问题讨论】:

    标签: android kotlin kotlin-coroutines coroutine


    【解决方案1】:

    对于suspend 函数,您应该使用withTransaction 而不是runInTransaction

    【讨论】:

    • 实现“androidx.room:room-ktx:$room_version”
    【解决方案2】:

    IO 绑定和其他长时间运行的操作(如数据库或 API 调用)被限制直接在主线程中运行(否则可能导致您的程序无响应)。协程就像轻量级线程,在线程内异步运行。

    我建议阅读 https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html 的 Coroutines 指南

    要回答您的问题,您需要设置一个协程范围和调度线程,以便您的协程在其上运行。最简单的是:

    GlobalScope.launch(Dispatchers.IO) {
        replaceAccounts(newAccounts)
    }
    

    它将在 IO 线程(处理 IO 任务的主线程之外的线程)上的 GlobalScope(协程的“生命周期”绑定到整个应用程序的生命周期)中运行您的协程。

    编辑 我确实喜欢@IR42 的回答。在此基础上,在这种情况下使用 withTransaction 允许 Room 处理执行数据库操作的线程,并有助于限制数据库的并发性。

    GlobalScope.launch(Dispatchers.Main) {
        replaceAccounts(newAccounts)
    }
    
    override suspend fun replaceAccounts(newAccounts: List<Account>) {
        database.withTransaction {
            database.accountDao().deleteAllAccounts() // I have the error on this line
            database.accountDao().insertAccounts(newAccounts) // Here too
        }
    }
    

    查看 Room 自己的一篇关于这篇文章的更多信息:https://medium.com/androiddevelopers/threading-models-in-coroutines-and-android-sqlite-api-6cab11f7eb90

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多