October 25, 2024
Chicago 12, Melborne City, USA
Android

@Transaction in Android Room seems to not working as expected


In below code seems that Flow is emitted between deleteAll and insertAll.. I expected to perform these methods together as a transaction. Am I missing something?

private const val RECENT_UPDATE_THRESHOLD_MS = 60_000L

@Dao
interface InboxMessageDao {
    @Query(
        "SELECT * FROM inbox_message " +
                "WHERE toEmail == (SELECT email FROM email_address WHERE isCurrent = 1) " +
                "AND (strftime('%s', 'now') * 1000 - cacheLastUpdate) < $RECENT_UPDATE_THRESHOLD_MS"
    )
    fun getAllFlow(): Flow<List<InboxMessageEntity>>

    @Insert
    suspend fun insertAll(messages: List<InboxMessageEntity>)

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

    @Query("SELECT cacheLastUpdate FROM inbox_message WHERE toEmail == :toEmail LIMIT 1")
    suspend fun getCacheLastUpdate(toEmail: String): Long?

    @Transaction // TODO: This fails tests sometimes, why?
    suspend fun refreshInboxMessages(newMessages: List<InboxMessageEntity>) {
        deleteAll()
        // Flow seems to be propagated here giving me sometimes empty list in androidTests
        insertAll(newMessages)
    }
}

I expect Flow being emitted after whole transaction performed.

PS. runInTransaction {} doesn’t fix this problem..



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video