skip to content

In Room, how does a DAO query returning Flow re-emit when a background sync inserts new messages, and why can it re-emit unchanged results?

level: middleimportance: must knowfreq 65%

answer

  1. tables, not rows
  2. triggers flag a modified table
  3. re-run the whole query after a write
  4. distinctUntilChanged on the collector side

basics

~20 s

Room tracks the tables a Flow query reads; after any write to one of them, it re-runs the whole query and emits the new result, even when the write touched rows outside it, so equal lists can arrive.

solid answer

~40 s

Room knows at compile time which tables a `@Query` reads. When a `Flow` returned by that DAO function starts being collected, Room's `InvalidationTracker` installs triggers on those tables, and after a write commits it checks which tables were modified. If one of the query's tables was, the `Flow` re-runs the entire query on Room's context and emits the full new result. That is how an inbox list collecting `observeInbox()` updates when a sync job inserts messages, with no manual refresh. The granularity is the table, not the row: marking an archived message as read re-runs the inbox query too, and it emits a list equal to the last one. Room documents this limitation and recommends `distinctUntilChanged()` when only real changes should reach the UI. LiveData and RxJava observable returns use the same invalidation.

code

kotlin · 10 lines
kotlin
@Dao
interface InboxDao {
    @Query("SELECT id, sender, subject, receivedAt, isRead FROM message WHERE folder = 'inbox' ORDER BY receivedAt DESC")
    fun observeInbox(): Flow<List<InboxRow>>
}

class InboxRepository(private val inboxDao: InboxDao) {
    // Re-runs after any write to `message`; drop lists equal to the previous one.
    val inbox: Flow<List<InboxRow>> = inboxDao.observeInbox().distinctUntilChanged()
}

go deeper

for a junior

Recall that a DAO function returning Flow keeps emitting: once at the start, then again after writes to the tables the query reads.

for a middle

Explain the chain: the table set from the SQL, triggers flagging modified tables, the check after a write, the full re-run, and why per-table tracking produces equal results.

for a senior

Show production judgment: distinctUntilChanged where duplicates cost work, narrow queries because every write re-runs them, one database instance per process, and conflation under bursts of writes.

for a principal

Discuss when table-level invalidation stops scaling, such as a hot table written constantly under many observers, and how a team would restructure tables or queries in response.

## The problem an observable query solves An offline-first inbox shows messages from a local Room database while a background sync job downloads new ones and inserts them. The screen must update when rows arrive, without the sync code knowing which screens are open. Room's answer is the **observable query**: a DAO function whose return type is `Flow<T>` (or `LiveData<T>`, or an RxJava `Flowable` or `Observable` through Room's integrations). The function is not `suspend`; it returns a stream immediately, and the work happens when someone collects it. ## How Room knows something changed Room's mechanism has three parts, all generated or managed by the library: 1. **The table set.** Room parses the SQL of each `@Query` at build time, so it knows which tables (and the tables behind any view) the query reads. That set is passed to the generated code. 2. **Triggers and a tracking table.** When collection starts, the `InvalidationTracker` installs SQLite triggers (`AFTER INSERT`, `AFTER UPDATE`, `AFTER DELETE`) on each observed table. A trigger flips an "invalidated" flag for its table in a small in-memory tracking table. Triggers are only kept for tables that some active collector is watching. 3. **A check after each write.** After Room finishes a write, whether a DAO `@Insert`, an `@Update` or a whole transaction, it reads the flags, resets them and notifies the `Flow`s whose tables were touched. The generated `Flow` is, in effect, the tracker's invalidation stream for those tables, conflated and mapped to "run the query again". It emits once at the start with the current rows, then once per invalidation. ## Why identical results re-emit The tracker works at **table** granularity. Room does not know whether the changed row matches the query's `WHERE` clause, so any write to the `message` table re-runs the inbox query: - marking an archived message as read re-runs a query filtered to `folder = 'inbox'`; - updating a column the query does not select re-runs it too; - a `Flow<Message?>` for one row re-emits when any other message changes. Room's own guidance names this limitation and recommends `distinctUntilChanged()` on the collected stream, which drops an emission equal to the previous one. Equality comes from the result type, so data classes, or lists of them, compare by content. The operator itself, and what other `Flow` operators do, belong to the Kotlin `Flow` material; the Room-specific part is knowing that re-emission is per table and that duplicates are expected. ## Behaviour worth knowing | Situation | What the `Flow` does | |---|---| | Collection starts | runs the query and emits the current result | | A write touches an observed table | re-runs the full query and emits the new result | | Several writes land while the collector is busy | emissions are conflated; the collector gets the latest result, not every step | | A transaction inserts 200 rows | observers are notified after the write completes, not per row | | A write from another process, or another `RoomDatabase` instance on the same file | not seen unless multi-instance invalidation is enabled with `enableMultiInstanceInvalidation()` | The conflation matters for a sync job that inserts messages one call at a time: a slow collector does not replay every intermediate list, it gets the newest one. If the sync wraps its inserts in one transaction, observers are notified after it completes and never render half a page of new mail. ## Writing it well - Keep the query narrow (select the columns the list needs) so each re-run is cheap; the re-run cost is paid on every write to the table. - Apply `distinctUntilChanged()` where duplicate lists would cause visible work, such as a list diff or an animation. - Build one `RoomDatabase` instance per process, so the sync job and the screen share one invalidation tracker. - Expose the stream from a repository and collect it in a lifecycle-aware way; how a ViewModel turns it into UI state is a `Flow` and architecture question, not a Room one. A good interview answer traces the chain end to end: the query's table set, the triggers that mark a table as modified, the re-run after a write, and the duplicate emissions that per-table tracking produces.

  • Does a Room Flow emit once per inserted row when a sync inserts 200 messages in one transaction?
    No. The triggers only flag the table as modified; Room checks the flags after the write completes and notifies the observing `Flow`s then. The query re-runs and emits the full list with all 200 messages. Outside a transaction, separate inserts can each cause an invalidation, but the generated `Flow` is conflated, so a busy collector receives the latest result rather than every intermediate one.
  • Why might an inbox Flow not update when the sync runs in a separate process?
    Room's invalidation tracker lives in each `RoomDatabase` instance. A write made through another instance, including one in another process, is not seen by this instance's tracker unless multi-instance invalidation is enabled on both with `enableMultiInstanceInvalidation()`. Keeping a single database instance per process avoids the problem within the app process.
  • How does a Room query returning LiveData decide when to re-run?
    It uses the same invalidation tracker: Room watches the tables the query reads and re-runs the query after a write to one of them, while the LiveData has active observers. The re-run is per table, so duplicate values can arrive there too, and LiveData's own `distinctUntilChanged` transformation filters them.

It is like subscribing to a mailing list rather than a topic: any post to the list sends you a fresh digest, even if the post is not about what you follow, so you skip digests identical to the last one.

  • Room only re-emits when a row inside the query's result set changes.
  • A Room Flow emits a diff of the changed rows rather than the full result.
  • The DAO function returning Flow must be suspend to observe changes.
  • You must call a refresh method after every insert for the list to update.
  • A Room Flow emits once for every row a transaction inserts.