首页 > 解决方案 > Android Room Compilation error suspend function @Transaction

问题描述

I'm having problems with suspend function in Room @Transaction

Versions:

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"

I also tried with 2.1.0-rc01.

Kotlin : 1.3

This is my DAO interface:

@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)
}

At compilation I get following error:

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.

I'm referring to this

If I remove suspend in all functions then it works.

Any help is appreciated :)

标签: android-roomkotlin-coroutines

解决方案


依赖项有问题。

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"

现在它起作用了。


推荐阅读