Skip to content

Lesson 8 of 9 · 26m

Room, DataStore, and Files: Local Storage That Survives Reality

Choose the right storage primitive, design migrations carefully, encrypt only where appropriate, and respect backup and deletion semantics.

Android gives you several ways to persist state because each solves a different problem. SharedPreferences became the junk drawer of a generation; Room became the answer to relational data; DataStore replaced preferences with typed, observable storage; files still matter for media, exports, caches, and attachments. Choosing incorrectly creates migrations, corruption, and data-loss bug reports that no amount of Compose polish will hide.

Use the storage ladder deliberately

Room       structured relational data, queries, sync state, entities
DataStore  small typed preferences, feature flags, onboarding state
Files      media, documents, cache blobs, exports
SavedState small restoration data for process death
Backend    authoritative shared or cross-device state

Do not store a growing JSON document in preferences because serialization was easy that afternoon. Preferences are not a document database.

Room schemas are contracts

Entities and migrations are part of your public durability surface:

@Entity(tableName = "orders", indices = [Index("serverId", unique = true)])
data class OrderEntity(
    @PrimaryKey val id: String,
    val serverId: String,
    val status: String,
    val updatedAt: Instant,
)

@Database(entities = [OrderEntity::class], version = 3)
abstract class AppDatabase : RoomDatabase() {
    abstract fun orders(): OrderDao
}

A destructive migration fallback may be acceptable for a cache, unacceptable for drafts or offline-created work. Write migration tests against exported schemas. Upgrades happen from every old version in the field, not just last week's.

Transactions model invariants

Sync operations often touch multiple tables. Wrap them:

@Transaction
suspend fun replaceOrders(serverOrders: List<ServerOrder>) {
    ordersDao.upsertAll(serverOrders.map { it.toEntity() })
    syncDao.setLastSuccessfulSync(Instant.now())
}

Without transactions a crash can leave rows updated but sync state stale, or the reverse. Later reconciliation becomes guesswork.

DataStore is observable, not instantaneous

Preferences DataStore uses coroutines and files. Do not block the main thread reading it, and do not treat every write as a transaction across unrelated keys:

val Context.settings: DataStore<Preferences> by preferencesDataStore("settings")

suspend fun setAnalyticsEnabled(enabled: Boolean) {
    context.settings.edit { it[booleanPreferencesKey("analytics_enabled")] = enabled }
}

Proto DataStore gives stronger typing but requires schema management. Either way, preferences are bad homes for large datasets or high-frequency counters.

Encryption, backup, and deletion are product behavior

Android Keystore can protect keys, but encrypting everything indiscriminately complicates backup, sharing, corruption recovery, and performance. Decide what data is sensitive. Configure android:allowBackup and backup rules deliberately. Implement account deletion honestly: local database rows, files, caches, sync queues, and server state all have lifetimes.

Field notes

  • Cache directories can be cleared by the system; do not store the only copy of user work there.
  • Database corruption and disk-full conditions exist in the real world; test low storage before release.
  • DatabaseMainThread queries fail for a reason. Move I/O off the main thread.
  • Auto-migrations are convenient until column renames and complex transformations need explicit migration logic.
  • A successful network response does not prove durable local persistence; write local state before declaring completion.

Was this lesson helpful?

Sign in to rate