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

Android Room start transaction from repository


I’m currently developing an Android app in Kotlin using Room for data storage.
In my repository class, I listen to changes to the database using Flows obtained from my dao and then verify, convert and publish the data to the rest of my app also using Flows.

However, I have some complex operations on the data that require more than one write to the database. If I just use the normal methods of the dao, Room may send partially updated data to the Flow, which may lead to crashes or wrong data in the UI. So I figured out that I needed to use a transaction to prevent that issue, but I could find only two ways to start a transaction:

  1. The withTransaction() method of the RoomDatabase class, which would require me to pass that class as a dependency to my repository
  2. The @Transaction annotation, which would require me to move some of my logic into the dao

Both options are not optimal, so I came up with the following method in my dao:

@Transaction
open suspend fun transaction(transaction: suspend () -> Unit): Unit = transaction()

It just takes a lambda and executes it in a transaction, which allows me to manage transactions from my repository using the following pattern:

dao.transaction {
  // Multiple database writes
}

Since my experience with Room and Kotlin is very limited, I just wanted to ask whether there are any drawbacks or better ways to solve this. Thanks.



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