QuarK
QuarK

Reputation: 1302

Room @Transaction not working with Flowable

I have a problem with using @Transaction annotation on my data source method. Looks like this annotation not working in my case.

I have a usual room database with DAO

@Database(entities = [MyEntity::class], version = 1)
abstract class MyDatabase : RoomDatabase() {
    abstract fun myDao(): MyDao
}

@Dao
interface myDao {
    @Insert
    fun insertAll(list: List<MyEntity>)
    
    @Query("SELECT * FROM MyEntity")
    fun observe(): Flowable<List<MyEntity>>

    @Query("DELETE FROM MyEntity")
    fun clear()
}

Problem appears in my data source when I do consistently clear() and insertAll()

class MyDataSource(database: MyDatabase) {
    private val myDao = database.myDao()

    @Transaction
    fun updateMyEntity(items: List<MyEntity>) {
        myDao.clear()
        myDao.insertAll(items)
    }

    fun observeMyEntity(): Flowable<List<MyEntity>> {
        return myDao.observe()
    }
}

When I call updateMyEntity(), I get two results in my subscription on oberveMyEntity(). The first result is empty list and the second one is inserted list. I expected to get only inserted list as I added annotation @Transaction to method updateMyEntity(). Is this annotation not working in my case?

I saw in docs the following information, but I am not sure is it my case or not.

If the query is asynchronous (e.g. returns a {@link androidx.lifecycle.LiveData LiveData} or RxJava {@code Flowable}), the transaction is properly handled when the query is run, not when the method is called.

Putting this annotation on an {@link Insert}, {@link Update} or {@link Delete} method has no impact because those methods are always run inside a transaction. Similarly, if a method is annotated with {@link Query} but runs an INSERT, UPDATE or DELETE statement, it is automatically wrapped in a transaction and this annotation has no effect.

The problem disappears if make database a property and wrap calls clear() and insertAll() with database.runInTransaction { }.

Upvotes: 0

Views: 1190

Answers (1)

IR42
IR42

Reputation: 9682

Transaction can only be used for Dao methods

Upvotes: 1

Related Questions