【问题标题】:Android Room Compilation error suspend function @TransactionAndroid Room 编译报错挂起函数@Transaction
【发布时间】:2019-06-03 09:30:23
【问题描述】:

我在 Room @Transaction 中的挂起功能遇到问题

版本:

room_version = "2.1.0-alpha04"
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-coroutines:$room_version"
kapt "androidx.room:room-compiler:$room_version"

我也尝试使用 2.1.0-rc01。

科特林:1.3

这是我的 DAO 界面:

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(sifrBl: SifrBl)

@Query("DELETE FROM sifrbl")
suspend fun deleteAll()

@Transaction
suspend fun setSifrBl(sifrBl: SifrBl){
    deleteAll()
    insert(sifrBl)
}

编译时出现以下错误:

Method annotated with @Transaction must not return deferred/async return type androidx.lifecycle.LiveData. Since transactions are thread confined and Room cannot guarantee that all queries in the method implementation are performed on the same thread, only synchronous @Transaction implemented methods are allowed. If a transaction is started and a change of thread is done and waited upon then a database deadlock can occur if the additional thread attempts to perform a query. This restrictions prevents such situation from occurring.

我指的是this

如果我在所有功能中删除暂停,那么它可以工作。

任何帮助表示赞赏:)

【问题讨论】:

  • 向我们展示您的依赖关系
  • 不确定您要查找的依赖项。写了与 Room 和 Coroutines 相关的内容。
  • 尝试将房间版本更改为2.1.0-rc01

标签: android-room kotlin-coroutines


【解决方案1】:

依赖项有问题。

room_version = "2.1.0-rc01"

    //Room
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"

// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"

// Test helpers
testImplementation "androidx.room:room-testing:$room_version"

现在可以了。

【讨论】:

  • 你救了我的命。如果没有正确的依赖关系,事务就无法工作。
【解决方案2】:

查看注释处理器的源代码后,我可以说给定代码不可能产生所述错误,因为它只会在方法返回 LiveData<*> 对象时触发。 (reference)

作为参考,任何以某种方式返回 LiveData 对象、RxJava 对象或 Guava 的 ListenableFuture 对象的 @Transaction 方法都会触发此异常,因为它们可能会在从方法返回后导致突变。请注意,这是一个黑名单,任何延迟执行的对象都会同样存在问题,但不会触发错误。

【讨论】:

    【解决方案3】:

    接受的答案对我不起作用。我必须打开该方法,然后它才起作用。检查生成的类,我可以看到为什么必须打开该方法,因为它在生成的类中被覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多