Data cheat sheet
Key ideas
- Room Flow queries re-emit after any write to the table they read, not just matching rows; add
distinctUntilChanged()to drop duplicates. @Upsertupdates a row in place;@Insert(onConflict = REPLACE)deletes then inserts, soON DELETE CASCADEchildren vanish.- Bump
@Database(version)for every schema change; Room compares a hash and fails on existing installs at first query. - DataStore: one instance per file, read-modify-write inside
editorupdateData, catchIOExceptionondataand rethrow the rest. - Repository exposes
Flow<DomainModel>andsuspendfunctions; mapping (toDomain,toEntity) lives in the data layer, not the ViewModel. - Paging 3:
RemoteMediatorwrites to Room, Room'sPagingSourcereads; applymap/filterbeforecachedIn(viewModelScope). - Suspend DAO functions and Flow queries are main-safe; no
withContext(Dispatchers.IO)is needed for Room or Retrofit calls. @Transactionordb.withTransaction { }wraps multi-step writes; without it a crash between calls leaves partial data on disk.- Auto-migrations need exported schema JSON for both versions; renames require
@RenameColumnin anAutoMigrationSpecor the build fails. @RawQueryskips compile-time checking; pass user input as bind arguments, never by string concatenation.
APIs at a glance
| API or term | Use it for |
|---|---|
@Upsert | Insert or update a row in place without deleting children; use instead of @Insert(onConflict = REPLACE) for sync. |
@Transaction | Wrap multi-step DAO writes or @Relation queries so they commit atomically. |
withTransaction { } | Coroutine extension on RoomDatabase for multi-step writes inside a repository. |
Flow<List<T>> from @Query | Re-emits after any write to the table; pair with distinctUntilChanged(). |
@TypeConverters | Register on @Database to store non-column types (e.g. Instant as Long). |
@ColumnInfo(defaultValue = ...) | Required when adding a NOT NULL column via migration; must match the SQL default. |
AutoMigrationSpec / @RenameColumn | Tell Room how to rename a column; without it the build fails. |
MigrationTestHelper | From room-testing; runs migrations on a real device's SQLite in instrumented tests. |
preferencesDataStore / dataStore | Delegate to create a DataStore once per file; two instances throw IllegalStateException. |
ReplaceFileCorruptionHandler | Replaces a corrupted DataStore file with a default and lets reads continue. |
RemoteMediator | Fetches from network and writes to Room; returns MediatorResult.Success or Error. |
cachedIn(viewModelScope) | Caches PagingData across configuration changes; apply after map/filter. |
Snippets
Room entity and DAO: Flow query + Upsert
@Entity(tableName = "articles")
data class ArticleEntity(
@PrimaryKey val id: Long,
val authorId: Long,
val title: String,
val body: String,
val publishedAt: Long,
)
@Dao
interface ArticleDao {
@Query("SELECT * FROM articles ORDER BY publishedAt DESC")
fun observeAll(): Flow<List<ArticleEntity>>
@Query("SELECT * FROM articles WHERE authorId = :authorId ORDER BY publishedAt DESC")
fun observeByAuthor(authorId: Long): Flow<List<ArticleEntity>>
@Upsert
suspend fun upsertAll(articles: List<ArticleEntity>)
@Query("DELETE FROM articles")
suspend fun clearAll()
}DataStore preferences with migration and corruption handler
val Context.settingsStore: DataStore<Preferences> by preferencesDataStore(
name = "settings",
corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() },
produceMigrations = { ctx -> listOf(SharedPreferencesMigration(ctx, "legacy_settings")) },
)
val DARK_MODE = booleanPreferencesKey("dark_mode")
suspend fun Context.toggleDarkMode() {
settingsStore.edit { prefs -> prefs[DARK_MODE] = !(prefs[DARK_MODE] ?: false) }
}RemoteMediator: network to Room
// Inside class ArticleMediator(api, db) : RemoteMediator<Int, ArticleEntity>()
override suspend fun load(loadType: LoadType, state: PagingState<Int, ArticleEntity>): MediatorResult {
val afterId: Long? = when (loadType) {
LoadType.REFRESH -> null
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> state.lastItemOrNull()?.id
?: return MediatorResult.Success(endOfPaginationReached = true)
}
return try {
val page = api.articles(afterId = afterId, limit = state.config.pageSize)
db.withTransaction {
if (loadType == LoadType.REFRESH) db.articleDao().clearAll()
db.articleDao().upsertAll(page.map { it.toEntity() })
}
MediatorResult.Success(endOfPaginationReached = page.isEmpty())
} catch (e: IOException) {
MediatorResult.Error(e)
}
}Repository: map DTO to domain, upsert into Room
data class Article(val id: Long, val title: String, val body: String)
data class ArticleDto(val id: Long, val authorId: Long, val title: String, val content: String, val publishedAt: Long)
fun ArticleEntity.toDomain() = Article(id = id, title = title, body = body)
fun ArticleDto.toEntity() = ArticleEntity(id, authorId, title, body = content, publishedAt = publishedAt)
class OfflineArticleRepository(
private val dao: ArticleDao,
private val api: ArticleApi, // suspend fun fetchArticles(): List<ArticleDto>
) {
fun observeAll(): Flow<List<Article>> =
dao.observeAll().map { entities -> entities.map { it.toDomain() } }
suspend fun refresh() {
dao.upsertAll(api.fetchArticles().map { it.toEntity() })
}
}Rules of thumb
- Prefer
@Upsertover@Insert(onConflict = REPLACE)when syncing rows that have foreign-key children. - Never create more than one DataStore instance for the same file; declare it once as a top-level delegate or
@Singleton. - Never expose
Flow<Entity>orFlow<Dto>from the Repository; map to a domain model in the data layer. - Prefer
@TransactionorwithTransaction { }for any multi-step write; without it a crash leaves partial data. - Never call
runBlocking { dataStore.data.first() }on the main thread; collect the Flow in a coroutine instead. - Prefer
distinctUntilChanged()on Room Flow queries to avoid redundant UI recompositions.
Gotchas
- Using @Insert(onConflict = REPLACE) to sync rows with children. REPLACE deletes the old row before inserting the new one, so
ON DELETE CASCADEchildren disappear; use@Upsertto update in place. - Not bumping @Database(version) after changing an entity. Room's schema hash check fails on existing installs at the first query; always increment the version for every released schema change.
- Creating two DataStore instances for one file. DataStore throws
IllegalStateExceptionon read or write; declare the store once as a top-level delegate or a@Singletonprovider. - Skipping cachedIn(viewModelScope) on PagingData. After rotation the list reloads from scratch and collecting the same
PagingDatatwice throws; applycachedInin the ViewModel after anymap/filter. - Adding a NOT NULL column without a matching @ColumnInfo(defaultValue). SQLite rejects
ALTER TABLE ... ADD COLUMN ... NOT NULLwithout a non-null default, and Room's schema validation fails if the entity default differs from the SQL default. - Returning the same PagingSource instance from pagingSourceFactory. An invalidated source cannot be reused and the factory call throws; the factory must create a new
PagingSourceevery time.
Quick interview answers
Why prefer @Upsert over @Insert(onConflict = REPLACE) for sync?
REPLACE deletes the conflicting row and inserts a new one, so ON DELETE CASCADE foreign keys delete that row's children. @Upsert updates the row in place, preserving all child rows.
What happens when a Room Flow query's table receives a write?
Room re-emits the Flow after any write to the table, even if the WHERE clause filters out the changed row. Add distinctUntilChanged() to drop repeated identical results and avoid unnecessary recompositions.
How do you handle a corrupted DataStore file?
Set corruptionHandler = ReplaceFileCorruptionHandler { default } on the DataStore delegate. It replaces the file with the default value and subsequent reads succeed without crashing.
Why must Paging 3's pagingSourceFactory return a new instance each time?
A PagingSource is invalidated after use and cannot be reused; returning the same instance throws. The factory must create a fresh source on every call.
What is the role of RemoteMediator in Paging 3?
It fetches data from the network and writes it into Room, returning MediatorResult.Success or MediatorResult.Error. The Room-backed PagingSource then reads the updated table, keeping a single source of truth.
When do you need withContext(Dispatchers.IO) in a Repository?
Room suspend DAO functions and Retrofit suspend calls are already main-safe, so no context switch is needed. Use withContext only around blocking I/O or CPU-heavy work, with an injected dispatcher so tests can replace it.