Data cheat sheet

Revise Android data layer: Room entities, DAOs, migrations, DataStore, Repository pattern, and Paging 3 for offline-first apps.

Key ideas

  1. Room Flow queries re-emit after any write to the table they read, not just matching rows; add distinctUntilChanged() to drop duplicates.
  2. @Upsert updates a row in place; @Insert(onConflict = REPLACE) deletes then inserts, so ON DELETE CASCADE children vanish.
  3. Bump @Database(version) for every schema change; Room compares a hash and fails on existing installs at first query.
  4. DataStore: one instance per file, read-modify-write inside edit or updateData, catch IOException on data and rethrow the rest.
  5. Repository exposes Flow<DomainModel> and suspend functions; mapping (toDomain, toEntity) lives in the data layer, not the ViewModel.
  6. Paging 3: RemoteMediator writes to Room, Room's PagingSource reads; apply map/filter before cachedIn(viewModelScope).
  7. Suspend DAO functions and Flow queries are main-safe; no withContext(Dispatchers.IO) is needed for Room or Retrofit calls.
  8. @Transaction or db.withTransaction { } wraps multi-step writes; without it a crash between calls leaves partial data on disk.
  9. Auto-migrations need exported schema JSON for both versions; renames require @RenameColumn in an AutoMigrationSpec or the build fails.
  10. @RawQuery skips compile-time checking; pass user input as bind arguments, never by string concatenation.

APIs at a glance

API or termUse it for
@UpsertInsert or update a row in place without deleting children; use instead of @Insert(onConflict = REPLACE) for sync.
@TransactionWrap 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 @QueryRe-emits after any write to the table; pair with distinctUntilChanged().
@TypeConvertersRegister 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 / @RenameColumnTell Room how to rename a column; without it the build fails.
MigrationTestHelperFrom room-testing; runs migrations on a real device's SQLite in instrumented tests.
preferencesDataStore / dataStoreDelegate to create a DataStore once per file; two instances throw IllegalStateException.
ReplaceFileCorruptionHandlerReplaces a corrupted DataStore file with a default and lets reads continue.
RemoteMediatorFetches 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 @Upsert over @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> or Flow<Dto> from the Repository; map to a domain model in the data layer.
  • Prefer @Transaction or withTransaction { } 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 CASCADE children disappear; use @Upsert to 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 IllegalStateException on read or write; declare the store once as a top-level delegate or a @Singleton provider.
  • Skipping cachedIn(viewModelScope) on PagingData. After rotation the list reloads from scratch and collecting the same PagingData twice throws; apply cachedIn in the ViewModel after any map/filter.
  • Adding a NOT NULL column without a matching @ColumnInfo(defaultValue). SQLite rejects ALTER TABLE ... ADD COLUMN ... NOT NULL without 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 PagingSource every 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.

Go deeper