solaza
solaza

Reputation: 1291

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 :)

Upvotes: 1

Views: 3553

Answers (3)

mustapha jide
mustapha jide

Reputation: 41

The accepted answer didn't work for me. I had to make the method open and then it worked. Checking the generated class, I can see why it's necessary to make the method open since it is overridden in the generated class.

Upvotes: 2

solaza
solaza

Reputation: 1291

There was something wrong with dependencies.

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"

Now it works.

Upvotes: 3

Kiskae
Kiskae

Reputation: 25573

After looking at the source code of the annotation processor I can say it is impossible for the given code to produce the stated error, since it would only trigger if the method was returning a LiveData<*> object. (reference)

For reference, any @Transaction method which in some way returns a LiveData object, an RxJava object or Guava's ListenableFuture object would trigger this exception since they may cause mutations after returning from the method. Note that this is a blacklist and any object that defers execution would be equally problematic, but would not trigger an error.

Upvotes: 0

Related Questions