skip to content

Room Database

Android's SQLite layer, with compile-checked DAOs, annotated entities, relations and versioned migrations. Asked because local persistence is where offline behavior and upgrades work or corrupt data.

on this pageshow

explore

questions

page 1 of 2

In Room, what does declaring a DAO function suspend change, and on which thread does its query run when called from the main thread?

level: juniorimportance: must knowfreq 70%

answer

  1. main-safe from the caller's side
  2. Room switches context on its own
  3. the builder's query coroutine context
  4. Room 3.0 makes it mandatory

basics

~10 s

A suspend DAO function is main-safe: Room moves the query to its own coroutine context (Dispatchers.IO by default in Room 3.0, the query executor in Room 2.x) and resumes the caller with the result.

solid answer

~40 s

Room generates the body of a `suspend` DAO function so that it switches to the database's own coroutine context before it touches a connection, then resumes the caller on its original dispatcher. That is why a ViewModel can call `messageDao.markRead(id)` inside `viewModelScope.launch` on the main thread without blocking it and without wrapping it in `withContext(Dispatchers.IO)`. In Room 3.0 that context comes from `setQueryCoroutineContext` and defaults to `Dispatchers.IO` on Android. In Room 2.x it is built from the query executor, a shared background pool unless you call `setQueryExecutor`, or from `setQueryCoroutineContext`, available since 2.7.0. Room 3.0 also makes `suspend` mandatory for every DAO function that does not return a reactive type, while 2.x still compiles blocking functions, which throw on the main thread unless `allowMainThreadQueries()` is set.

code

kotlin · 14 lines
kotlin
@Dao
interface MessageDao {
    @Query("UPDATE message SET isRead = 1 WHERE id = :id")
    suspend fun markRead(id: Long): Int
}

class InboxViewModel(private val messageDao: MessageDao) : ViewModel() {
    fun onMessageOpened(id: Long) {
        // Launched on the main thread; Room switches to its query context itself.
        viewModelScope.launch {
            messageDao.markRead(id)
        }
    }
}

go deeper

for a junior

Recall that a suspend DAO function is safe to call from the main thread because Room switches threads itself, and that the caller resumes where it started.

for a middle

Explain the generated withContext call, the default context in each major (Dispatchers.IO in Room 3.0, the query executor in 2.x) and how setQueryCoroutineContext overrides it.

for a senior

Show you can move a 2.x codebase to Room 3.0's suspend-unless-reactive rule: which functions gain suspend, which callers move into coroutines, and why allowMainThreadQueries is not a fix.

for a principal

Weigh whether a team should ever override Room's default query context, for instance a bounded dispatcher, against the cost of a second threading policy to maintain.

## What `suspend` changes on a Room DAO function A **DAO** (data access object) is the interface or abstract class annotated with `@Dao` whose functions Room implements at build time. When one of those functions is marked `suspend`, Room generates an implementation that is **main-safe**: any coroutine may call it, including one running on the main thread, because Room itself moves the database work onto a background context before it opens or borrows a connection. When the query is done, the calling coroutine resumes on the dispatcher it came from, holding the result. For an Android engineer this means the UI layer does not manage threads for database work: - `viewModelScope.launch { messageDao.markRead(id) }` is safe on the main thread. - Wrapping that call in `withContext(Dispatchers.IO)` is redundant, because Room already switches. - The function reads like ordinary sequential code: insert, then read back, then update the UI state. The `suspend` keyword alone does not move work off a thread; the **generated code** does. Room's implementation wraps the query in a `withContext` call that targets the database's own context. A hand-written `suspend` function that performs blocking I/O would still block whatever thread it runs on. ## Where the query actually runs The two majors pick the background context differently: | | Room 2.8.5 (`androidx.room`) | Room 3.0 (`androidx.room3`) | |---|---|---| | Default context for suspend DAO calls | built from the query executor, a shared background thread pool unless you set one | `Dispatchers.IO` on Android | | How to override it | `setQueryExecutor` and `setTransactionExecutor`, or `setQueryCoroutineContext` (added in 2.7.0), never both | `setQueryCoroutineContext` only; the `Executor` setters are gone | | Blocking (non-suspend) one-shot DAO functions | compile, and throw `IllegalStateException` on the main thread unless `allowMainThreadQueries()` is set | do not compile unless the return type is reactive | Inside a transaction block a DAO call joins the transaction instead of opening a new one: Room 2.x runs it on the transaction's own thread, and Room 3.0 hands it the connection already confined to the calling coroutine. The transaction APIs are a separate question; the point here is that Room's context switch never takes a DAO call out of an enclosing transaction. ## Room 3.0: suspend unless reactive Room 3.0 requires coroutines. The release notes put it plainly: DAO functions have to be suspending unless they return a reactive type, such as a `Flow` or a custom DAO return type. Moving a 2.x DAO to 3.0 therefore follows a short sequence: 1. Add `suspend` to every one-shot function: inserts, updates, deletes and single reads. 2. Move each caller into a coroutine, for example a ViewModel's `viewModelScope` or a coroutine-based background worker. 3. Leave functions that return `Flow` as plain functions; the `Flow` is already the asynchronous part, and collecting it runs the query on Room's context. 4. Register DAO return type converters for LiveData, RxJava, Paging or Guava returns, which no longer work out of the box. Plain return types such as row ids, counts and lists stay the same; only the `suspend` modifier in front of them becomes mandatory. ## Configuring the context `setQueryCoroutineContext` takes a `CoroutineContext` that must contain a dispatcher; without one, Room throws `IllegalArgumentException`. In Room 3.0 that context runs all asynchronous work, including `Flow` emissions and invalidation tracker notifications. In Room 2.x the builder accepts either executors or a coroutine context, and calling both kinds of setter throws `IllegalArgumentException`. Teams usually leave the default; an override is for a bounded dispatcher or a test that needs to control where Room's work runs. ## Mistakes interviewers listen for - Claiming that `suspend` by itself moves work off the main thread; Room's generated `withContext` does. - Wrapping every DAO call in `withContext(Dispatchers.IO)` "to be safe", which only adds a context switch. - Reaching for `allowMainThreadQueries()` to silence a 2.x crash instead of making the function `suspend`. - Assuming Room 3.0 still accepts `setQueryExecutor`; it was removed, and `setQueryCoroutineContext` is the replacement. - Believing the caller resumes on Room's background thread; it resumes on its own dispatcher. A clear answer names the generated context switch, the default context of the major in use, and Room 3.0's rule that a non-reactive DAO function must be `suspend`.

  • In Room 3.0, can you still configure an Executor for queries?
    No. Room 3.0 removed `setQueryExecutor` and `setTransactionExecutor` from the builder. You pass a `CoroutineContext` containing a dispatcher to `setQueryCoroutineContext`, and Room uses it for queries, `Flow` emissions and invalidation notifications. If you never call it, Room uses `Dispatchers.IO` on Android. Room 2.x already offered `setQueryCoroutineContext` from 2.7.0, but there it was one choice beside the executors.
  • Why does a Room 2.x DAO call crash on the main thread when the same query marked suspend does not?
    A blocking DAO function runs on the caller's thread, and Room 2.x checks for the main thread and throws `IllegalStateException` ("Cannot access database on the main thread...") unless `allowMainThreadQueries()` was set. A `suspend` function instead switches to Room's background context before running the query, so the check never sees the main thread.

  • The suspend keyword alone moves the query onto a background thread.
  • Every suspend DAO call must still be wrapped in withContext(Dispatchers.IO).
  • After a suspend DAO call, the caller continues on Room's background thread.
  • Room 3.0 still lets you pass an Executor through setQueryExecutor.
  • allowMainThreadQueries() is the normal fix for a main-thread database crash.

Assumes Room 3.0 (androidx.room3): non-reactive DAO functions must be suspend and the default query context on Android is Dispatchers.IO; Room 2.8.5 also compiles blocking DAO functions and derives the context from its query executor.

open as a page

In Room, how do @Insert, @Update, @Delete and @Query DAO functions differ, and what can each one return?

level: juniorimportance: must knowfreq 78%

basics

~20 s

@Insert, @Update and @Delete take entity objects and Room writes the SQL, matching rows by primary key; @Query runs SQL you write. Inserts can return the new rowid as Long, updates and deletes an Int row count.

open as a page

In Room, what does annotating a Kotlin data class with @Entity declare, and how does @Database tie the entities together?

level: juniorimportance: must knowfreq 80%

basics

~20 s

@Entity declares a SQLite table: one table per class, one column per persisted property, keyed by its @PrimaryKey. @Database lists those entity classes with a schema version, and Room's compiler generates the database that creates and checks the tables.

open as a page

In Room 3.0, how do you store an Instant property on an entity, and where do you register the converter that makes it work?

level: juniorimportance: must knowfreq 62%

basics

~10 s

Room 3.0 stores an Instant through two @ColumnTypeConverter functions, Instant to Long epoch millis and back, registered with @ColumnTypeConverters on the @Database class so every entity and DAO can use them.

open as a page

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%

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.

open as a page

In Room, what does @Insert(onConflict = OnConflictStrategy.REPLACE) do to an existing row with the same key, and how does @Upsert differ?

level: middleimportance: must knowfreq 66%

basics

~20 s

REPLACE resolves the clash by deleting the existing row and inserting the new one, so ON DELETE CASCADE actions fire. @Upsert tries the insert and, on a uniqueness conflict, updates the row by primary key, returning -1 for updated rows.

open as a page

In Room, how do you write and register a Migration, and which migrations run for a user still on schema version 4?

level: middleimportance: must knowfreq 72%

basics

~20 s

Subclass Migration(startVersion, endVersion), run the schema SQL in migrate() and register it with addMigrations(). On open, Room reads the stored version and chains migrations up to the @Database version, taking the furthest step that does not overshoot.

open as a page

In Room, how do you load each artist with all of their albums through @Relation, and why does that DAO function need @Transaction?

level: middleimportance: must knowfreq 62%

basics

~20 s

Room fills a result class pairing an @Embedded Artist with a @Relation List<Album> matched on artistId. Room runs the artist query and then a separate album query, so @Transaction keeps both reads on one consistent database state.

open as a page

After a Room schema bump to version 7, some upgrading users crash on launch with IllegalStateException; how do you tell a missing migration from a wrong one, and fix each?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Read the message. 'A migration from 5 to 7 was required but not found' means no registered path: add the missing Migration. 'Migration didn't properly handle' means a path ran but the tables differ from the entities: fix that migration's SQL.

open as a page

In Room, what does @Embedded do to an entity's table, and when do you need its prefix parameter?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Room's @Embedded flattens a value object's properties into columns of the containing entity's own table. When two embedded properties share a type, their column names collide, so prefix prepends a distinct string to every column of one of them.

open as a page

How do you test that a Room DAO's Flow query re-emits after an insert, using an in-memory database and runTest?

level: middleimportance: should knowfreq 40%

basics

~10 s

Build the database with Room.inMemoryDatabaseBuilder, insert inside runTest, then await the Flow with first { condition } rather than toList(), because Room's Flow never completes and re-emits asynchronously on Room's own dispatcher.

open as a page

In Room, what does the annotation processor verify about a @Query's SQL, its :name parameters and its return type at build time?

level: middleimportance: should knowfreq 55%

basics

~20 s

Room prepares each @Query against the schema its entities define, so unknown tables or columns and SQL syntax errors fail the build; it binds :name placeholders to same-named parameters and checks result columns against the return type.

open as a page

In Room, how do you declare a composite primary key and a unique index on an entity, and what does each one generate?

level: middleimportance: should knowfreq 45%

basics

~20 s

A composite key goes in @Entity(primaryKeys = [...]) and becomes a PRIMARY KEY(a, b) table constraint; a unique index goes in @Entity(indices = [Index(value = [...], unique = true)]) and becomes a separate CREATE UNIQUE INDEX statement.

open as a page

In Room, what does @ForeignKey with onDelete = CASCADE declare on a child entity, and why does Room warn about an unindexed child column?

level: middleimportance: should knowfreq 50%

basics

~20 s

@ForeignKey adds a FOREIGN KEY clause to the child table's CREATE TABLE, so SQLite deletes a recipe's ingredients when the recipe is deleted. Room warns about a missing child index because every parent delete or key change would scan the whole child table.

open as a page

In Room, what CREATE TABLE statement does an @Entity generate, and how do nullability, @PrimaryKey(autoGenerate) and @ColumnInfo shape it?

level: middleimportance: should knowfreq 50%

basics

~20 s

Room writes CREATE TABLE IF NOT EXISTS with one column per property: the Kotlin type picks the affinity, a non-null type adds NOT NULL, autoGenerate makes an INTEGER PRIMARY KEY AUTOINCREMENT, and @ColumnInfo sets the name, affinity, collation, index and DEFAULT.

open as a page

In Room 3.0, how does writing a Migration or AutoMigrationSpec callback differ from Room 2.x, and how do you run SQL in it?

level: middleimportance: should knowfreq 35%

basics

~10 s

In Room 3.0, Migration.migrate is an abstract suspend function that receives an androidx.sqlite SQLiteConnection instead of a SupportSQLiteDatabase. You run statements with execSQL and read with prepare and step; AutoMigrationSpec.onPostMigrate changed the same way.

open as a page

In Room, how do you read each playlist with its songs when playlists share songs, using @Relation with a @Junction cross-reference entity?

level: middleimportance: should knowfreq 45%

basics

~10 s

Room needs a cross-reference entity holding playlistId and songId pairs, and a result class whose @Relation sets associateBy = Junction(PlaylistSongCrossRef::class). Room reads the songs through that junction table; the DAO function needs @Transaction.

open as a page

In Room, when would you return Map<Artist, List<Album>> from a JOIN query instead of an @Relation result class?

level: middleimportance: should knowfreq 28%

basics

~20 s

Room's multimap return type groups one JOIN query's rows into a Map, so SQL can filter, order and aggregate across both tables. Choose it when the screen needs that, or a count via @MapColumn; choose @Relation for nested reads without hand-written joins.

open as a page

How does Room store an enum status property when you write no converter, and when would you switch that built-in converter off?

level: middleimportance: should knowfreq 42%

basics

~10 s

Room's built-in enum converter stores the constant's name() as text, so renaming a constant breaks old rows. Teams disable it with BuiltInColumnTypeConverters(enums = DISABLED) (Room 2.x: BuiltInTypeConverters) to force an explicit, stable encoding.

open as a page

Moving a Room 2.x codebase to Room 3.0, what changes for its column type converters, and what stays the same?

level: middleimportance: should knowfreq 32%

basics

~10 s

Room 3.0 renames the converter family: @TypeConverter becomes @ColumnTypeConverter, with @ColumnTypeConverters, @ProvidedColumnTypeConverter, @BuiltInColumnTypeConverters and addColumnTypeConverter in androidx.room3. Scopes, built-ins, validation and stored data stay the same.

open as a page

Moving an app's DAOs from Room 2.x to Room 3.0, what happens to functions returning LiveData, RxJava types, PagingSource or plain blocking results?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Room 3.0 compiles a DAO function only if it is suspend or returns a reactive type. Blocking results need suspend; LiveData, RxJava, PagingSource and ListenableFuture need their room3 artifact plus a DAO return type converter registered with @DaoReturnTypeConverters.

open as a page

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?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Wrap 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.

open as a page

In Room, what does @Transaction do on a DAO function with a body, and on which DAO functions is it pointless?

level: seniorimportance: should knowfreq 45%

basics

~20 s

On a DAO function with a body, @Transaction runs the whole body in one database transaction, committed unless an exception escapes. On @Insert, @Update, @Delete and write @Query functions it adds nothing: each already runs in a transaction.

open as a page

When an Android app moves from Room 2.x to Room 3.0, what changes in the Gradle setup and the database builder, and what does getSupportWrapper() bridge?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Room 3.0 moves to androidx.room3 artifacts and imports, runs only as a KSP processor that generates Kotlin, and opens databases through a SQLiteDriver instead of SupportSQLite; getSupportWrapper() from room3-sqlite-wrapper gives legacy code a SupportSQLiteDatabase over Room's connections.

open as a page

In Room, what does @AutoMigration need in order to generate a migration, and when must you supply an AutoMigrationSpec with @RenameColumn or @DeleteColumn?

level: seniorimportance: should knowfreq 45%

basics

~20 s

@AutoMigration(from, to) diffs the exported schema JSON of both versions, so exportSchema must stay on with a schema directory set. Additions usually migrate on their own; a renamed or deleted table or column needs an AutoMigrationSpec carrying @RenameColumn, @DeleteColumn, @RenameTable or @DeleteTable.

open as a page

How do you test Room migrations with MigrationTestHelper so that a fitness app's users on versions 4, 5 and 6 all reach version 7 with their data intact?

level: seniorimportance: should knowfreq 40%

basics

~20 s

MigrationTestHelper creates a database at an old version from its exported schema; you insert rows by SQL, then runMigrationsAndValidate(7, migrations) runs Room's path and checks the schema against version 7's JSON. Assert the data yourself, per start version.

open as a page

Room has no lazy loading: when a music app reads artists with their albums and each album's songs through nested @Relation classes, how many queries run, and what does that cost?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Room reads the whole artist, album and song graph eagerly: one parent query, then one query per relation level for each batch of up to 999 keys. It avoids one query per row, but loads every child row whether the screen shows it or not.

open as a page

A Room 3.0 events app marks its attendee-ids converter @ProvidedColumnTypeConverter and now crashes building the database; what is wrong, and how do you fix it?

level: seniorimportance: should knowfreq 28%

basics

~10 s

A @ProvidedColumnTypeConverter class must be supplied through addColumnTypeConverter(); without it, build() throws IllegalArgumentException saying a required column type converter is missing. Add the instance to every builder, including test builders.

open as a page

As the lead of a production Android app on Room 2.8, when would you move it to Room 3.0, and how would you stage the move?

level: principalimportance: should knowfreq 30%

basics

~20 s

Move when you need what only Room 3.0 brings, such as multiplatform targets or its new features, and can afford KSP-only builds and suspend DAOs. Stage it on 2.8 first, with setDriver, the SupportSQLite wrapper, KSP and suspend DAOs, then swap packages.

open as a page

showing 1–30 of 33