DataStore: preferences and proto
Why it matters
SharedPreferencesreads the file on first access and can block the calling thread, andapply()writes are flushed synchronously when an Activity stops, a known source of ANRs. It also gives no signal when a write fails.- DataStore exposes data as a
Flowand writes with a suspend function, so disk work never runs on the main thread, and I/O errors reach your code as exceptions. updateDataruns read-modify-write as one transaction, so two quick toggles cannot overwrite each other.- Interviewers ask when to choose Preferences versus typed DataStore, why a second instance crashes, and how you migrate existing
SharedPreferencesusers without losing their settings.
The simple explanation
SharedPreferencesis a shared notebook: anyone can read or write any page, writes may not be finished when you look, and a torn page is silently blank.- Preferences DataStore is a key-value notebook with one clerk: every change goes through the clerk, one at a time.
- Typed DataStore (Proto or JSON) is a printed form with a fixed layout: the fields and their types are defined in advance, and the clerk still handles every change.
DataStore stores a small amount of data in a single file and keeps it consistent. Its whole API is two members: val data: Flow<T> to read, and suspend fun updateData(transform: suspend (T) -> T): T to write. There are two flavours:
- Preferences DataStore (
DataStore<Preferences>): keys such asbooleanPreferencesKey("dark_mode"), no schema. You write withedit { prefs -> prefs[KEY] = true }, which is a wrapper overupdateData. - Typed DataStore (
DataStore<T>): you define the type and aSerializer<T>. The classic version uses Protocol Buffers (Proto DataStore, a.protoschema compiled into Java or Kotlin classes); the same API works with a@SerializableKotlin data class and kotlinx.serialization JSON.
How writes work. Writes are serialized: DataStore runs one transform at a time, always on the latest data. The new value is written to a temporary file and then swapped in, and data emits it only after the write succeeded. If the write throws, updateData throws to the caller and the file keeps its old content.
Rules. Never create more than one active DataStore for the same file in a process: DataStore throws IllegalStateException ("There are multiple DataStores active for the same file") when you read or write. The type T must be immutable. For access from more than one process, build every instance with MultiProcessDataStoreFactory.
| Preferences DataStore | Typed DataStore (Proto or JSON) | |
|---|---|---|
| Schema | None; keys defined in code | .proto file or @Serializable class |
| Type safety | Per key; a key's type is fixed, but nothing checks the overall shape | The whole object is typed |
| Setup | One dependency and a delegate | A serializer plus protobuf or kotlinx.serialization setup |
| Good for | A handful of flags and simple settings | Structured settings, nested values, lists of small items |
Neither is a database: DataStore rewrites the whole file on every update and has no queries or partial updates. Large or relational data belongs in Room.
Notes
- Create each DataStore once: the
preferencesDataStore(name = ...)ordataStore(fileName = ..., serializer = ...)delegate at the top level of a Kotlin file, or a@Singletonprovider in Hilt. Two active instances for one file throwIllegalStateException. - Keys come from typed factory functions:
booleanPreferencesKey,intPreferencesKey,stringPreferencesKey,stringSetPreferencesKeyand others. Reading a missing key returnsnull. datathrowsIOExceptionif the file cannot be read. Catch it in the repository withcatch { if (it is IOException) emit(default) else throw it }; anything else should still crash loudly.updateDataandeditthrow if the write fails, so call them where you can report the error, not fire-and-forget.- A typed
Serializer<T>hasdefaultValue,suspend fun readFrom(input: InputStream): Tandsuspend fun writeTo(t: T, output: OutputStream). ThrowCorruptionExceptionfromreadFromwhen the bytes cannot be parsed. - Without a handler, a corrupted file makes reads throw
CorruptionException.corruptionHandler = ReplaceFileCorruptionHandler { default }replaces the file with the default and carries on. SharedPreferencesMigration(context, "old_prefs_name")goes inproduceMigrations. It runs before the first read, copies the keys, and then deletes them from the old file, so it does not run again.- The
dataFlow emits the whole object on every change. Map it to the field you need and adddistinctUntilChanged()if one screen only cares about one value. - Avoid
runBlocking { dataStore.data.first() }on the main thread: it blocks on disk I/O, which is the problem DataStore was meant to remove. - DataStore files live under
files/datastore/and are included in Auto Backup by default; keep sensitive values in a separate file and exclude it.
Code example
Two real setups: a Preferences DataStore that migrates an old SharedPreferences file, and a typed DataStore that uses kotlinx.serialization JSON with a corruption handler. Each delegate is declared once at the top level.
import android.content.Context
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.DataStore
import androidx.datastore.core.Serializer
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.dataStore
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStore
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.serialization.SerializationException
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
// ---- Preferences DataStore: one instance per file, declared once ----
val Context.settingsStore: DataStore<Preferences> by preferencesDataStore(
name = "settings",
produceMigrations = { context -> listOf(SharedPreferencesMigration(context, "legacy_settings")) },
corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() },
)
private val DARK_MODE = booleanPreferencesKey("dark_mode")
// ---- Typed DataStore with kotlinx.serialization ----
@Serializable
data class UserProfile(val username: String = "", val onboardingDone: Boolean = false)
object UserProfileSerializer : Serializer<UserProfile> {
override val defaultValue = UserProfile()
override suspend fun readFrom(input: InputStream): UserProfile =
try {
Json.decodeFromString(UserProfile.serializer(), input.readBytes().decodeToString())
} catch (e: SerializationException) {
throw CorruptionException("Cannot read user profile", e)
}
override suspend fun writeTo(t: UserProfile, output: OutputStream) {
output.write(Json.encodeToString(UserProfile.serializer(), t).encodeToByteArray())
}
}
val Context.profileStore: DataStore<UserProfile> by dataStore(
fileName = "user_profile.json",
serializer = UserProfileSerializer,
corruptionHandler = ReplaceFileCorruptionHandler { UserProfile() },
)
// ---- Repository: the only class that touches the stores ----
class SettingsRepository(
private val settings: DataStore<Preferences>,
private val profile: DataStore<UserProfile>,
) {
val darkMode: Flow<Boolean> = settings.data
.catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e }
.map { prefs -> prefs[DARK_MODE] ?: false }
.distinctUntilChanged()
val userProfile: Flow<UserProfile> = profile.data
.catch { e -> if (e is IOException) emit(UserProfile()) else throw e }
// Read-modify-write in one transaction: rapid toggles cannot lose an update
suspend fun toggleDarkMode() {
settings.edit { prefs -> prefs[DARK_MODE] = !(prefs[DARK_MODE] ?: false) }
}
suspend fun completeOnboarding(name: String) {
profile.updateData { current -> current.copy(username = name, onboardingDone = true) }
}
}- Hilt or a manual container passes
context.settingsStoreandcontext.profileStoreinto the repository, so no other class creates a second instance. - The toggle reads and writes inside one
editblock. Reading the value fromdataand writing it back in a separate call is a lost update waiting to happen. UserProfileis an immutable data class;copybuilds a new value, which is what DataStore requires.- With Protocol Buffers instead,
readFromcallsUserProfile.parseFrom(input), catchesInvalidProtocolBufferException, and updates usetoBuilder()...build().
Run the idea in plain Kotlin
Two coroutines each add 1 to a stored counter. The naive version reads, suspends, then writes, so one update is lost. The second version runs each read-modify-write under a Mutex, which is the guarantee updateData gives you.
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class FakeStore(var value: Int = 0) {
private val lock = Mutex()
// Like updateData: one transform at a time, always on the latest value
suspend fun updateData(transform: suspend (Int) -> Int): Int = lock.withLock {
value = transform(value)
value
}
}
fun main() = runBlocking {
val naive = FakeStore()
val a = launch { val read = naive.value; yield(); naive.value = read + 1 }
val b = launch { val read = naive.value; yield(); naive.value = read + 1 }
joinAll(a, b)
println("naive read then write: " + naive.value)
val safe = FakeStore()
val c = launch { safe.updateData { current -> yield(); current + 1 } }
val d = launch { safe.updateData { current -> yield(); current + 1 } }
joinAll(c, d)
println("updateData: " + safe.value)
}Expected output:
naive read then write: 1
updateData: 2
In production
- A refactor replaced the top-level delegate with
PreferenceDataStoreFactory.create { context.preferencesDataStoreFile("settings") }insideSettingsRepository. - The repository was not scoped as a singleton, so two screens each created their own instance for the same file.
- The app crashed with
IllegalStateException: There are multiple DataStores active for the same fileas soon as the second screen read a setting.
- Moved creation into a Hilt
@Provides @Singletonfunction, so the app has exactly oneDataStore<Preferences>for that file. - Injected that instance into the repository instead of creating it there.
- Added a review rule: DataStore instances are only created in the one DI module that provides them.
- The team switched to Preferences DataStore and wrote a one-off loop in
Application.onCreatethat copied the old values withedit. - Startup sometimes raced with the first screen reading DataStore, which saw defaults. Users saw the onboarding again and their theme reset.
- On some devices the loop ran again after a crash and overwrote values the user had changed since.
- Replaced the loop with
produceMigrations = { listOf(SharedPreferencesMigration(it, "legacy_settings")) }on the delegate. - DataStore now runs the migration before the first read returns, and removes the migrated keys from the old file, so it never runs twice.
- Added a test that writes the old
SharedPreferencesfile, creates the DataStore and asserts the first emitted values match.
Common mistakes
- Creating more than one DataStore for the same file. DataStore throws
IllegalStateExceptionon read or write. Declare it once, as a top-level delegate or a singleton. - Read, then write in a separate call. Reading with
data.first()and writing with anothereditcan lose an update. Do the read and the write inside oneeditorupdateDatablock. - Catching every exception on
data. CatchIOExceptionand emit a default; rethrow the rest, or real bugs turn into silently empty settings. - Mutating the stored object. A mutable class (or a
MutableListfield) changed outsideupdateDatabreaks DataStore's consistency. Use immutable data classes andcopy. - Using DataStore as a database. Each update rewrites the whole file and every read loads the whole object. Lists that grow, or anything you need to query, belong in Room.
- Blocking the main thread to read a setting.
runBlocking { data.first() }brings the old ANR back. Collect the Flow, or read it in a coroutine during startup.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between Preferences DataStore and Proto DataStore?”
“How does DataStore handle data updates?”
“Why is SharedPreferences considered risky in modern Android code?”
“How would you migrate from SharedPreferences to DataStore?”
Quiz
What does a typed (Proto or JSON) DataStore need that Preferences DataStore does not?
Two screens each create a DataStore for the file settings.preferences_pb. What happens?
The data Flow fails because the file cannot be read. What should the repository do?
A dark-mode toggle reads the current value with data.first() and then calls edit to write the opposite. Users tapping fast sometimes see the toggle not flip. What is the fix?
0 of 4 answered
Mini task
Task: a settings repository with a migration
- Add
androidx.datastore:datastore-preferences, and declareval Context.settingsStore by preferencesDataStore(name = "settings", produceMigrations = { listOf(SharedPreferencesMigration(it, "your_old_prefs")) })at the top level of a file. - Define
booleanPreferencesKey("dark_mode")andstringPreferencesKey("user_id"). - Write a
SettingsRepositorythat takes theDataStore<Preferences>in its constructor and exposesdarkMode: Flow<Boolean>anduserId: Flow<String?>, catchingIOExceptionand emittingemptyPreferences(). - Add
suspend fun toggleDarkMode()that reads and writes inside oneeditblock, andsuspend fun setUserId(id: String). - In a ViewModel, expose
darkModewithstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)and collect it withcollectAsStateWithLifecycle(). - Before installing the new build, put a value in the old
SharedPreferencesfile; after installing, check that the screen shows it on first launch.
Done condition: there is exactly one place that creates the DataStore, tapping the toggle quickly never loses a flip, and the old setting appears after migration without any manual copy code.