DataStore: preferences and proto

Learn Jetpack DataStore in Android to master Preferences and Proto DataStore, atomic updates, error handling, and SharedPreferences migration. About 25 minutes.

Why it matters

  • SharedPreferences reads the file on first access and can block the calling thread, and apply() 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 Flow and writes with a suspend function, so disk work never runs on the main thread, and I/O errors reach your code as exceptions.
  • updateData runs 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 SharedPreferences users without losing their settings.

The simple explanation

  • SharedPreferences is 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:

  1. Preferences DataStore (DataStore<Preferences>): keys such as booleanPreferencesKey("dark_mode"), no schema. You write with edit { prefs -> prefs[KEY] = true }, which is a wrapper over updateData.
  2. Typed DataStore (DataStore<T>): you define the type and a Serializer<T>. The classic version uses Protocol Buffers (Proto DataStore, a .proto schema compiled into Java or Kotlin classes); the same API works with a @Serializable Kotlin 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 DataStoreTyped DataStore (Proto or JSON)
SchemaNone; keys defined in code.proto file or @Serializable class
Type safetyPer key; a key's type is fixed, but nothing checks the overall shapeThe whole object is typed
SetupOne dependency and a delegateA serializer plus protobuf or kotlinx.serialization setup
Good forA handful of flags and simple settingsStructured 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 = ...) or dataStore(fileName = ..., serializer = ...) delegate at the top level of a Kotlin file, or a @Singleton provider in Hilt. Two active instances for one file throw IllegalStateException.
  • Keys come from typed factory functions: booleanPreferencesKey, intPreferencesKey, stringPreferencesKey, stringSetPreferencesKey and others. Reading a missing key returns null.
  • data throws IOException if the file cannot be read. Catch it in the repository with catch { if (it is IOException) emit(default) else throw it }; anything else should still crash loudly.
  • updateData and edit throw if the write fails, so call them where you can report the error, not fire-and-forget.
  • A typed Serializer<T> has defaultValue, suspend fun readFrom(input: InputStream): T and suspend fun writeTo(t: T, output: OutputStream). Throw CorruptionException from readFrom when 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 in produceMigrations. It runs before the first read, copies the keys, and then deletes them from the old file, so it does not run again.
  • The data Flow emits the whole object on every change. Map it to the field you need and add distinctUntilChanged() 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.settingsStore and context.profileStore into the repository, so no other class creates a second instance.
  • The toggle reads and writes inside one edit block. Reading the value from data and writing it back in a separate call is a lost update waiting to happen.
  • UserProfile is an immutable data class; copy builds a new value, which is what DataStore requires.
  • With Protocol Buffers instead, readFrom calls UserProfile.parseFrom(input), catches InvalidProtocolBufferException, and updates use toBuilder()...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

Crash after moving DataStore into a class
  • A refactor replaced the top-level delegate with PreferenceDataStoreFactory.create { context.preferencesDataStoreFile("settings") } inside SettingsRepository.
  • 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 file as soon as the second screen read a setting.
The fix
  • Moved creation into a Hilt @Provides @Singleton function, so the app has exactly one DataStore<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.
Settings lost after migrating from SharedPreferences
  • The team switched to Preferences DataStore and wrote a one-off loop in Application.onCreate that copied the old values with edit.
  • 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.
The fix
  • 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 SharedPreferences file, creates the DataStore and asserts the first emitted values match.

Common mistakes

  • Creating more than one DataStore for the same file. DataStore throws IllegalStateException on 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 another edit can lose an update. Do the read and the write inside one edit or updateData block.
  • Catching every exception on data. Catch IOException and emit a default; rethrow the rest, or real bugs turn into silently empty settings.
  • Mutating the stored object. A mutable class (or a MutableList field) changed outside updateData breaks DataStore's consistency. Use immutable data classes and copy.
  • 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

  1. Add androidx.datastore:datastore-preferences, and declare val Context.settingsStore by preferencesDataStore(name = "settings", produceMigrations = { listOf(SharedPreferencesMigration(it, "your_old_prefs")) }) at the top level of a file.
  2. Define booleanPreferencesKey("dark_mode") and stringPreferencesKey("user_id").
  3. Write a SettingsRepository that takes the DataStore<Preferences> in its constructor and exposes darkMode: Flow<Boolean> and userId: Flow<String?>, catching IOException and emitting emptyPreferences().
  4. Add suspend fun toggleDarkMode() that reads and writes inside one edit block, and suspend fun setUserId(id: String).
  5. In a ViewModel, expose darkMode with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false) and collect it with collectAsStateWithLifecycle().
  6. Before installing the new build, put a value in the old SharedPreferences file; 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.

Next: Repository pattern