14-datastore.md
.codex/skills/compose-kotlin-agent-skills/references/14-datastore.md
1---2name: datastore3description: >4 Preferences DataStore vs Proto DataStore, SharedPreferences migration, typed keys,5 coroutine-safe reads/writes, security-crypto encryption. Use when replacing6 SharedPreferences or persisting user settings.7version: "2.2.0"8updated: "2026-05-21"9---1011# DataStore — Preferences, Proto, Migration, Encryption1213## Pinned versions (2026)1415```toml16datastore = "1.1.7"17security-crypto = "1.1.0"18```1920```kotlin21implementation("androidx.datastore:datastore-preferences:1.1.7")22implementation("androidx.datastore:datastore:1.1.7")23implementation("androidx.security:security-crypto:1.1.0")24```2526## Preferences DataStore vs Proto DataStore2728| | Preferences DataStore | Proto DataStore |29|---|---|---|30| Schema | Key-value (`booleanPreferencesKey`, etc.) | Protobuf message |31| Use when | Settings, flags, simple prefs | Typed structured config |32| Type safety | Keys are typed | Full proto schema |3334---3536## WRONG / RIGHT 1 — SharedPreferences.apply() on main thread3738```kotlin39// WRONG — apply() is async but still blocks binder; commit() blocks main thread40fun saveTheme(context: Context, dark: Boolean) {41 context.getSharedPreferences("settings", Context.MODE_PRIVATE)42 .edit()43 .putBoolean("dark_mode", dark)44 .apply()45}4647// RIGHT — suspend edit on DataStore IO dispatcher48private val Context.dataStore by preferencesDataStore(name = "settings")4950suspend fun saveTheme(context: Context, dark: Boolean) {51 context.dataStore.edit { prefs ->52 prefs[booleanPreferencesKey("dark_mode")] = dark53 }54}55```5657---5859## WRONG / RIGHT 2 — Reading prefs synchronously in Composable6061```kotlin62// WRONG — blocks composition; SharedPreferences on main thread63@Composable64fun ThemeToggle() {65 val context = LocalContext.current66 val dark = context.getSharedPreferences("settings", MODE_PRIVATE)67 .getBoolean("dark_mode", false)68 Switch(checked = dark, onCheckedChange = { /* ... */ })69}7071// RIGHT — Flow from DataStore, collect with lifecycle72@Composable73fun ThemeToggle(vm: SettingsViewModel = hiltViewModel()) {74 val dark by vm.isDarkMode.collectAsStateWithLifecycle(initialValue = false)75 Switch(76 checked = dark,77 onCheckedChange = { vm.onEvent(SettingsEvent.DarkModeChanged(it)) }78 )79}8081class SettingsViewModel @Inject constructor(82 private val settingsRepo: SettingsRepository83) : ViewModel() {84 val isDarkMode: StateFlow<Boolean> = settingsRepo.isDarkMode85 .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)86}87```8889---9091## WRONG / RIGHT 3 — Untyped string keys everywhere9293```kotlin94// WRONG — typo-prone magic strings95dataStore.edit { it["dark_mode"] = true } // won't compile on Preferences — good96// but agents write:97prefs.edit().putString("user_id", id).apply()9899// RIGHT — typed keys in one object100object SettingsKeys {101 val DARK_MODE = booleanPreferencesKey("dark_mode")102 val USER_ID = stringPreferencesKey("user_id")103}104105suspend fun DataStore<Preferences>.setDarkMode(enabled: Boolean) {106 edit { it[SettingsKeys.DARK_MODE] = enabled }107}108109val DataStore<Preferences>.darkModeFlow: Flow<Boolean> =110 data.map { it[SettingsKeys.DARK_MODE] ?: false }111```112113---114115## WRONG / RIGHT 4 — SharedPreferences migration without handler116117```kotlin118// WRONG — dual writes, race on first launch119fun migrate(context: Context) {120 val sp = context.getSharedPreferences("legacy", MODE_PRIVATE)121 val dark = sp.getBoolean("dark", false)122 context.dataStore.edit { it[SettingsKeys.DARK_MODE] = dark }123}124125// RIGHT — produceMigrations on DataStore builder126private val Context.dataStore by preferencesDataStore(127 name = "settings",128 produceMigrations = { context ->129 listOf(130 object : DataMigration<Preferences> {131 override suspend fun cleanUp() {132 context.deleteSharedPreferences("legacy")133 }134 override suspend fun shouldMigrate(currentData: Preferences): Boolean =135 !currentData.contains(SettingsKeys.DARK_MODE)136137 override suspend fun migrate(currentData: Preferences): Preferences {138 val legacy = context.getSharedPreferences("legacy", MODE_PRIVATE)139 return currentData.toMutablePreferences().apply {140 this[SettingsKeys.DARK_MODE] = legacy.getBoolean("dark", false)141 }142 }143 }144 )145 }146)147```148149---150151## WRONG / RIGHT 5 — Storing secrets in plain Preferences DataStore152153```kotlin154// WRONG — token in unencrypted Preferences DataStore155dataStore.edit { it[stringPreferencesKey("auth_token")] = token }156157// RIGHT — EncryptedSharedPreferences for legacy OR encrypt value before Proto store158// For tokens prefer EncryptedSharedPreferences migration path or Android Keystore + Proto159160val masterKey = MasterKey.Builder(context)161 .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)162 .build()163164val encryptedPrefs = EncryptedSharedPreferences.create(165 context,166 "secure_prefs",167 masterKey,168 EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,169 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM170)171// Migrate to DataStore only after encrypting at rest or use hardware-backed keys172```173174---175176## Decision matrix177178| Need | Choice |179|---|---|180| Boolean / String / Int settings | Preferences DataStore |181| Structured config with schema | Proto DataStore |182| Legacy SharedPreferences | `produceMigrations` + delete SP after |183| Auth tokens | Keystore + EncryptedSharedPreferences or encrypted Proto |184| Read in UI | `Flow` → `stateIn` in VM → `collectAsStateWithLifecycle` |185186## Anti-patterns summary187188- Never `commit()` or `apply()` in new code — migrate to DataStore.189- Never read DataStore synchronously in `@Composable` — always Flow.190- Never duplicate writes to both SP and DataStore after migration completes.191