In Room, what does declaring a DAO function suspend change, and on which thread does its query run when called from the main thread?
answer
- main-safe from the caller's side
- Room switches context on its own
- the builder's query coroutine context
- Room 3.0 makes it mandatory
basics
~10 sA 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 sRoom 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@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
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.
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.
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.
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.