In Room, how do you make a sync job's message inserts, unread-count update and sync-cursor write atomic across several suspend DAO calls?
answer
- one block, one commit
- the writer connection
- withTransaction in 2.x
- withWriteTransaction in Room 3.0
basics
~20 sWrap the DAO calls in one transaction block: withWriteTransaction in Room 3.0 (withTransaction in Room 2.x). It commits only if the block completes; an exception rolls every write back, and observers are notified after the commit.
solid answer
~50 sEach suspend DAO call is its own transaction, so three calls can leave the inbox half-synced if the second one fails. In Room 3.0 you wrap them in `db.withWriteTransaction { ... }`: Room acquires its single writer connection, begins an `IMMEDIATE` transaction, and the DAO calls made inside the block run on that same connection, because it is confined to the block's coroutine. If the block returns, Room commits; if it throws, or calls `rollback(result)`, every write is rolled back and the exception propagates. In Room 2.x the equivalent is the `withTransaction` extension, part of `room-runtime` since 2.7.0. Observable queries are notified after the commit, so the inbox re-runs with the whole page and never shows half of it. Keep network calls out of the block: it holds the writer connection, by default the only one, while it waits.
code
kotlin · 8 linessuspend fun applyPage(db: InboxDatabase, page: SyncPage) {
// Network work happens before this function is called.
db.withWriteTransaction {
db.messageDao().insertAll(page.messages)
db.threadDao().recountUnread(page.threadIds)
db.syncStateDao().saveCursor(page.nextCursor)
} // commits here; any exception above rolls all three back
}go deeper
Recall that several DAO writes become all-or-nothing when wrapped in one transaction block, and that an exception undoes them.
Explain how the block's DAO calls join the transaction: Room 2.x runs them on the transaction thread, Room 3.0 reuses the connection confined to the block's coroutine.
Show the production shape: fetch outside, write inside, let failures escape for retry, never hold the writer connection across a network wait, and know Room 3.0's API names.
Discuss how long write transactions in sync code affect every other writer in the app, and how a team splits large syncs into pages that each commit atomically.
## Why separate DAO calls are not enough A sync job for an offline-first inbox typically does three things per page: insert the new messages, update each thread's unread count, and store the sync cursor that says where the next page starts. Each `suspend` DAO call runs in its own short transaction. If the job inserts the messages and then crashes or throws before writing the cursor, the next run downloads the same page again; if the unread-count update fails, the badge disagrees with the list. The fix is a **transaction** that covers all three calls, so they commit together or not at all. ## Room 3.0: `withWriteTransaction` and friends Room 3.0 replaced the 2.x transaction helpers with connection-based APIs, all of them `suspend`: | API | What it does | |---|---| | `withWriteTransaction { }` | acquires the writer connection and runs the block in an `IMMEDIATE` transaction | | `withReadTransaction { }` | acquires a reader connection and runs the block in a `DEFERRED` transaction | | `useWriterConnection { }` / `useReaderConnection { }` | lend a connection (a `Transactor`) for custom transaction types or raw statements | The rules that make `withWriteTransaction` work for DAO calls: - The connection is **confined to the block's coroutine**. A DAO call made from inside the block finds that connection already in place and uses it, so it joins the transaction instead of opening its own. - The block **commits** when it returns normally. It **rolls back** when it throws, and the exception propagates to the caller; `rollback(result)` on the `TransactionScope` rolls back deliberately and returns a value. - Calling `withWriteTransaction` again inside the block starts a **nested transaction** (a savepoint) on the same connection, still governed by the outer one. - A Room 3.0 database has **one writer connection** by default (`setMultipleConnectionPool` can change that). While the block runs, other writers wait for it; a caller that waits too long to acquire a connection gets a `SQLiteException` for the timeout. ## Room 2.x: `withTransaction` In Room 2.x the helper is the `RoomDatabase.withTransaction` extension, which lived in `room-ktx` and has been part of `room-runtime` since 2.7.0. It marks the transaction successful unless the block throws or the coroutine is cancelled. Under the hood it takes a thread from Room's transaction executor and dispatches the block's suspending DAO calls onto it, and Room runs at most one such transaction at a time; others queue. Its documentation recommends that every DAO function called inside be `suspend`, and forbids blocking database calls from any coroutine other than the block's own. When a 2.x database is configured with a `SQLiteDriver`, the documentation points to `useWriterConnection` with `immediateTransaction` instead. ## What observers see Observable queries are refreshed **after** the write completes. DAO writes inside the block do not notify observers one by one; an inbox collecting a `Flow` of messages re-runs its query after the commit with the whole page in place, instead of rendering messages without their unread counts. Readers on other connections see only committed data, so a concurrent read never sees half of the sync. ## Writing the sync step 1. Fetch the page from the network **before** the transaction starts. 2. Open `withWriteTransaction` and make only database calls inside it. 3. Insert the messages, update the unread counts, write the cursor. 4. Let an exception escape on failure, so Room rolls back and the job can retry. Common mistakes: - Awaiting the network inside the block, which holds the writer connection (by default the only one) while it waits and stalls other writes in the app. - Handing a DAO call to a coroutine launched in some other scope from inside the block: that coroutine does not carry the transaction's connection in its context, so its call runs outside the transaction, and a write there waits for the writer the transaction holds. - Catching the exception inside the block "to keep going", which commits the partial work the transaction was meant to prevent. - Expecting Room 3.0 to keep `runInTransaction` or the `RoomDatabase.withTransaction` extension; they were replaced by `withWriteTransaction` and its siblings. An `@Transaction` DAO function that calls the other DAO functions is the alternative when all the calls live in one DAO; it belongs with the DAO material. The coroutine-level helper is the tool when the writes span several DAOs, as a sync job's usually do.
- In Room 3.0, how do you roll back a withWriteTransaction block without throwing an exception?The block runs with a `TransactionScope` receiver, and calling `rollback(result)` on it ends the transaction with a rollback and makes the block return `result`. It suits a sync step that discovers, after some writes, that the page is stale and should be discarded without treating that as an error.
- Why should the network request stay outside the transaction block?By default a Room 3.0 database has a single writer connection, and `withWriteTransaction` holds it for the whole block. Suspending on a network call inside it keeps other writes in the app waiting, and callers that wait too long for a connection fail with a `SQLiteException` timeout. Fetch first, then open the transaction for database work only.
- Each DAO call inside the block still commits on its own.
- Room rolls back the transaction but swallows the exception.
- Doing the network request inside the transaction is fine because it suspends.
- Room 3.0 keeps runInTransaction for coroutine code.
- Observers re-emit after every DAO call inside the transaction.
Assumes Room 3.0 (androidx.room3), where withWriteTransaction, withReadTransaction and the use*Connection functions replace Room 2.x's RoomDatabase.withTransaction extension and runInTransaction; useReaderConnection and useWriterConnection already existed from Room 2.7.0.