skip to content

DataStore

The coroutine and Flow replacement for SharedPreferences, as Preferences or typed Proto DataStore. Interviewers ask what was wrong with SharedPreferences, and DataStore is the expected answer.

on this pageshow

explore

questions

6

In Preferences DataStore, how do you create the store, define typed keys, and read and write a reading app's theme and font size?

level: juniorimportance: must knowfreq 64%

answer

  1. top-level Context extension property
  2. preferencesDataStore delegate
  3. intPreferencesKey, stringPreferencesKey
  4. data.map with a default
  5. edit gives MutablePreferences

basics

~10 s

Declare one top-level preferencesDataStore delegate, define keys with stringPreferencesKey or intPreferencesKey, read by mapping the data Flow (a missing key gives null), and write inside the suspending edit block on MutablePreferences.

solid answer

~30 s

You declare `val Context.readerSettings by preferencesDataStore(name = "reader_settings")` once, at the top level of a Kotlin file, which keeps a single instance backed by `files/datastore/reader_settings.preferences_pb`. Each value gets a typed key, such as `stringPreferencesKey("theme")` or `intPreferencesKey("font_size")`. Reading is `readerSettings.data.map { it[FONT_SIZE] ?: 16 }`: `data` is a Flow and a missing key returns `null`, so you supply the default. Writing is `readerSettings.edit { it[FONT_SIZE] = 18 }`, a suspend call that hands you a `MutablePreferences` copy, applies it as one transaction and returns after the change is on disk. `remove(key)` deletes a value.

code

kotlin · 32 lines
kotlin
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

val Context.readerSettings: DataStore<Preferences> by preferencesDataStore(name = "reader_settings")

object ReaderKeys {
    val THEME = stringPreferencesKey("theme")
    val FONT_SIZE = intPreferencesKey("font_size")
}

class ReaderSettingsRepository(private val context: Context) {
    val theme: Flow<String> =
        context.readerSettings.data.map { prefs -> prefs[ReaderKeys.THEME] ?: "light" }

    val fontSize: Flow<Int> =
        context.readerSettings.data.map { prefs -> prefs[ReaderKeys.FONT_SIZE] ?: 16 }

    suspend fun setFontSize(size: Int) {
        context.readerSettings.edit { prefs -> prefs[ReaderKeys.FONT_SIZE] = size }
    }

    suspend fun resetTheme() {
        context.readerSettings.edit { prefs -> prefs.remove(ReaderKeys.THEME) }
    }
}

go deeper

for a junior

Recall the four pieces: the top-level preferencesDataStore delegate, typed key functions, data.map with a default, and edit with MutablePreferences.

for a middle

Explain that edit is a transaction built on updateData and returns after the write is on disk, and why the read-modify-write belongs inside one edit block.

for a senior

Point out the traps: keys compared by name only, a delegate declared per class, and no exception handling on the data Flow.

for a principal

Decide how the team organises keys and files: one keys object per store, separate stores per concern, and a rule against calling DataStore from UI code.

## Creating the store **Preferences DataStore** is the key-value flavour of Jetpack DataStore, in the `androidx.datastore:datastore-preferences` artifact. You create it with the `preferencesDataStore` **property delegate**: ```kotlin val Context.readerSettings: DataStore<Preferences> by preferencesDataStore(name = "reader_settings") ``` - Declare it **once, at the top level** of a Kotlin file. The delegate holds a single instance and builds it lazily from the application context the first time it is read. - The `name` becomes the file `files/datastore/reader_settings.preferences_pb` inside the app's private files directory. - The delegate also accepts an optional `corruptionHandler`, a `produceMigrations` lambda and a `scope`; the default scope is `CoroutineScope(Dispatchers.IO + SupervisorJob())`. Declaring the delegate inside a class or a composable creates a new instance each time, which breaks DataStore's one-instance-per-file rule. ## Typed keys Preferences DataStore has no schema, so every value is addressed by a **typed key** built from a factory function. The key's type parameter fixes what `get` returns. | Factory | Value type | |---|---| | `intPreferencesKey` | `Int` | | `longPreferencesKey` | `Long` | | `floatPreferencesKey` / `doublePreferencesKey` | `Float` / `Double` | | `booleanPreferencesKey` | `Boolean` | | `stringPreferencesKey` | `String` | | `stringSetPreferencesKey` | `Set<String>` | Keys are compared by **name only**. If `"font_size"` was written as an `Int` and later read through `stringPreferencesKey("font_size")`, the read fails with a `ClassCastException`. Keep keys in one object so each name has exactly one type. ## Reading through the data Flow `readerSettings.data` is a `Flow<Preferences>` that emits the current persisted preferences and again after every successful write. You map it to the value the UI needs: ```kotlin val fontSize: Flow<Int> = context.readerSettings.data.map { it[FONT_SIZE] ?: 16 } ``` - `prefs[key]` returns `null` when the key was never written, so the default lives at the read site. - The Flow can throw an `IOException` when the file cannot be read; that error path is a later topic. - For a one-shot value inside a coroutine, `data.first()` takes a single snapshot. ## Writing with edit `edit` is a suspending extension on `DataStore<Preferences>`: ```kotlin suspend fun setFontSize(size: Int) { context.readerSettings.edit { prefs -> prefs[FONT_SIZE] = size } } ``` 1. DataStore reads the current preferences and gives you a **`MutablePreferences` copy**. 2. Your block sets values with `prefs[key] = value`, or deletes them with `remove(key)` or `clear()`. 3. When the block returns, the copy is frozen and written as **one transaction**, serialized with every other write. 4. `edit` returns once the data is on disk; if the write fails, it throws. Two rules from the API docs: changes are not in DataStore until the block completes, and you must not keep a reference to the `MutablePreferences` and mutate it later, because that will not change the stored data. `edit` is built on `updateData`, so both share the same transactional guarantees. ## Where the file lives and what is in it The delegate writes `files/datastore/<name>.preferences_pb`. The contents are a protobuf-encoded map of key names to typed values, not XML, so you do not edit it by hand or read it with another API; the docs say not to use the file outside DataStore. Every `edit` rewrites the whole file, which is cheap for a few dozen settings and the reason Preferences DataStore is meant for small data. Because the files sit under the app's private files directory, they are included in Android Auto Backup by default. If one store holds something that should not leave the device, give it its own file so backup rules can exclude it. ## Using it from the app's layers The Android guide recommends keeping DataStore in the **data layer**: - a repository owns the store and exposes `Flow` values such as `fontSize` and suspend functions such as `setFontSize`; - a ViewModel turns those flows into UI state and launches the writes in its own scope; - the UI observes that state and never touches DataStore directly. That keeps the single instance in one place, keeps disk work off the UI code, and makes the repository easy to replace with a fake in tests. ## Mistakes interviewers listen for - Declaring the delegate in an `Activity` or `ViewModel` instead of at the top level. - Treating a missing key as `0` or `""` instead of `null`. - Reusing one key name with two different types. - Calling `edit` without a coroutine, or wrapping it in `runBlocking` on the main thread. - Collecting `data` directly inside a composable instead of exposing it from a ViewModel or repository.

  • Why must the preferencesDataStore delegate sit at the top level of a file?
    The delegate object holds the single instance. A top-level property means one delegate per process, so every caller shares one `DataStore` for the file. Declared inside a class, each instance of that class gets its own delegate and its own `DataStore` on the same file, and the second one throws an `IllegalStateException` on its first read or write.
  • How do you increment a counter safely with Preferences DataStore?
    Do the read and the write in the same `edit` block: `edit { it[COUNT] = (it[COUNT] ?: 0) + 1 }`. The block receives the current value inside a serialized transaction, so two concurrent increments cannot both read the same old value. Reading with `data.first()` and then calling `edit` separately reintroduces the lost-update race.

  • Declaring the preferencesDataStore delegate inside each Activity is fine.
  • A missing Preferences key returns 0 for an Int key.
  • Keys with the same name but different types are stored separately.
  • edit returns as soon as the in-memory value changes, like apply().
  • You can keep the MutablePreferences from edit and change it later.
open as a page

What was wrong with SharedPreferences that Jetpack DataStore was built to fix, and what does DataStore guarantee instead?

level: juniorimportance: must knowfreq 72%

basics

~20 s

SharedPreferences has a synchronous API that invites main-thread disk I/O, signals write failures poorly and can return unpersisted state. DataStore reads through a Flow and writes through suspending, serialized transactions that finish only once data is on disk.

open as a page

When would you choose a typed DataStore with a Serializer over Preferences DataStore, and how do updateData and data.first() behave there?

level: middleimportance: should knowfreq 46%

basics

~20 s

Choose typed DataStore when the data is a structured object that needs a schema and type safety. Its Serializer supplies defaultValue, readFrom and writeTo; updateData runs a serialized, atomic transform on an immutable value; data.first() takes one snapshot.

open as a page

In Jetpack DataStore, why does a second instance on the same file throw IllegalStateException, and how do you share one file across processes?

level: seniorimportance: should knowfreq 38%

basics

~20 s

DataStore allows one active instance per file in a process; a second one fails on its first read or write with "There are multiple DataStores active for the same file". Across processes, every process must use MultiProcessDataStoreFactory, one instance each.

open as a page

As the Android lead moving a shipped app from SharedPreferences to DataStore, how would you plan the migration and choose Preferences or typed DataStore as the team default?

level: principalimportance: should knowfreq 33%

basics

~20 s

Register a SharedPreferencesMigration in produceMigrations, keep key names and types identical, switch every reader in the same release because cleanUp deletes the old keys, and plan for rollback. Default to Preferences DataStore for flat settings, typed DataStore for structured objects.

open as a page

When crash reports show CorruptionException from a DataStore file, what happens by default, and how do ReplaceFileCorruptionHandler and a catch on data change it?

level: seniorimportance: nice to knowfreq 27%

basics

~20 s

By default DataStore does not recover: every read of a corrupt file throws CorruptionException, and updates fail too. A ReplaceFileCorruptionHandler writes replacement data over the file and swallows the error; a catch on data only hides it.

open as a page