Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 104 ยท Local Data

DataStore and Settings

Store app settings with Jetpack DataStore: Preferences vs Proto, Flow-based reads, transactional writes and migrating from SharedPreferences.

Almost every app has a few small pieces of data that are not worth a database: the chosen theme, whether onboarding is finished, the last selected tab, a sort order. For years these lived in SharedPreferences. It is simple, but it has well-known problems: reads can block the main thread, writes with apply() give no result, errors are swallowed, and there is no safe way to observe changes.

Jetpack DataStore is the modern replacement. It stores data in a file, exposes it as a Kotlin Flow, and updates it with suspend functions inside a transaction. In this lesson you will meet the two flavors (Preferences and Proto), see how reads and writes work, and learn to migrate old SharedPreferences data. DataStore needs the Android SDK, so its code here is read-only. The TryIt blocks are Kotlin stand-ins (using coroutines on Piston) that reproduce the behavior: typed keys, a flow of snapshots and all-or-nothing edits.

Preferences DataStore

Preferences DataStore is a typed key-value store. You declare one instance per file as a property on Context, and define keys with a type:

Kotlin
// read-only example: needs Android
private val Context.settingsStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

object SettingsKeys {
    val DARK_MODE = booleanPreferencesKey("dark_mode")
    val SORT_ORDER = stringPreferencesKey("sort_order")
    val LAUNCH_COUNT = intPreferencesKey("launch_count")
}

The by preferencesDataStore delegate guarantees a single instance for the file. Two DataStore objects pointing at the same file break its guarantees, so never create more than one per file. Supported key types are Int, Long, Float, Double, Boolean, String and Set<String>. Keys carry the type, so intPreferencesKey("x") and stringPreferencesKey("x") are different keys that happen to share a name.

Reading is a flow. Each time anything in the file changes, data emits a fresh immutable Preferences snapshot:

Kotlin
// read-only example: needs Android
class SettingsRepository(private val store: DataStore<Preferences>) {

    val darkMode: Flow<Boolean> = store.data
        .catch { e ->
            if (e is IOException) emit(emptyPreferences()) else throw e
        }
        .map { prefs -> prefs[SettingsKeys.DARK_MODE] ?: false }
        .distinctUntilChanged()

    suspend fun setDarkMode(enabled: Boolean) {
        store.edit { prefs -> prefs[SettingsKeys.DARK_MODE] = enabled }
    }
}

Three habits are visible here. First, a missing key gives null, so you supply the default in the map. Second, the catch handles a corrupt or unreadable file by falling back to defaults instead of crashing the collector; other exceptions are rethrown. Third, distinctUntilChanged() stops the UI from being notified when an unrelated key changed.

edit { } is a suspend function. It runs your lambda on a background thread, so you can call it from viewModelScope.launch without worrying about the main thread. The lambda receives a MutablePreferences; you can set keys, remove them or clear() everything.

Transactions

Everything inside one edit block is applied atomically. Either all changes are written, or, if the lambda throws, none are. Concurrent edits are serialized, so two coroutines incrementing a counter cannot lose an update:

Kotlin
// read-only example: needs Android
suspend fun registerLaunch() {
    store.edit { prefs ->
        val count = prefs[SettingsKeys.LAUNCH_COUNT] ?: 0
        prefs[SettingsKeys.LAUNCH_COUNT] = count + 1
    }
}

The read-modify-write happens inside the block, which is what makes it safe. Reading the value outside with data.first() and then writing it back is the classic mistake, because another edit can slip in between.

The first TryIt is a stand-in for this model. Key<T> plays the typed keys, Prefs is an immutable snapshot, and FakeDataStore publishes snapshots through a StateFlow and serializes edits with a mutex. A collector prints each distinct value of one key, so you can see that writing a different key does not wake it up.

Kotlin Typed keys and a flow of snapshots (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The stand-in publishes a new snapshot even when a value is rewritten unchanged; the distinctUntilChanged() in the pipeline is what keeps the output quiet, exactly as in the real repository code above.

Proto DataStore and typed objects

Preferences DataStore has no schema. Nothing stops you from writing a string where another screen expects an int, and a typo in a key name creates a new silent setting. Proto DataStore stores a whole typed object and gives you one class for all settings. Despite the name, you do not need Protocol Buffers: any class works if you provide a Serializer. With kotlinx.serialization it looks like this:

Kotlin
// read-only example: needs Android
@Serializable
data class UserSettings(
    val darkMode: Boolean = false,
    val sortOrder: String = "newest",
    val pinnedIds: List<Long> = emptyList()
)

object UserSettingsSerializer : Serializer<UserSettings> {
    override val defaultValue = UserSettings()

    override suspend fun readFrom(input: InputStream): UserSettings =
        try {
            Json.decodeFromString(UserSettings.serializer(), input.readBytes().decodeToString())
        } catch (e: SerializationException) {
            throw CorruptionException("Cannot read settings", e)
        }

    override suspend fun writeTo(t: UserSettings, output: OutputStream) {
        output.write(Json.encodeToString(UserSettings.serializer(), t).encodeToByteArray())
    }
}

val Context.userSettings: DataStore<UserSettings> by dataStore(
    fileName = "user_settings.json",
    serializer = UserSettingsSerializer
)

suspend fun togglePin(store: DataStore<UserSettings>, id: Long) {
    store.updateData { old ->
        old.copy(pinnedIds = if (id in old.pinnedIds) old.pinnedIds - id else old.pinnedIds + id)
    }
}

The data class must be immutable: updateData gives you the old value and you return a new one with copy. The defaults live in the class, so adding a field in a later version just works for old files, as long as the new field has a default. You read it with store.data, which is a Flow<UserSettings>. For the serialization side, see kotlinx.serialization basics.

Need Choose
A handful of independent flags and strings, quick to set up Preferences DataStore
Many related settings, a list, nested objects, compile-time safety Proto DataStore
Large data, queries, relations Room instead (Room basics)

DataStore reads the whole file into memory on first access, so it is for small data. If you find yourself storing hundreds of rows in it, you want a database.

SharedPreferences basics

Before DataStore, every Android app stored small settings in SharedPreferences. You will meet it in old tutorials, libraries and codebases, and you need it to migrate, so here is the whole API. (Files, internal and external storage are covered in Files and Storage, so this section sticks to key-value settings.)

Kotlin
// read-only example: needs Android
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)

// Read: synchronous, answered from an in-memory copy after the first load
val token: String? = prefs.getString("token", null)
val launches: Int = prefs.getInt("launches", 0)

// Write: collect changes in an Editor, then publish them
prefs.edit()
    .putString("token", "abc123")
    .putInt("launches", launches + 1)
    .apply()

getSharedPreferences(name, mode) opens (or creates) an XML file under your app's private storage. MODE_PRIVATE is the only mode you should use; the old world-readable modes were removed. Inside an activity, getPreferences(MODE_PRIVATE) gives you one file named after that activity, and the AndroidX Preference library creates a default file for settings screens.

apply() versus commit()

Both publish the editor's changes; they differ in how they treat the disk.

apply() commit()
Updates the in-memory map Immediately Immediately
Writes the file Later, in the background Now, on the calling thread
Return value None true if the write succeeded
Safe on the main thread Mostly (see below) No, it blocks on disk I/O

Use apply() unless you must know the write succeeded. apply() is not free: the framework waits for pending writes to finish when an activity stops or a service ends, so a big file can still cause a stutter or an ANR there. Keep SharedPreferences small, and do not store lists or JSON blobs in it.

Listeners and the session pattern

registerOnSharedPreferenceChangeListener tells you when a key changes, which lets a screen react to a settings change made elsewhere. Hold the listener in a field (the preferences object keeps only a weak reference, so an anonymous listener can be garbage collected and silently stop working) and unregister it when the screen goes away.

The classic use is session management: a small class that wraps the file so the rest of the app never touches keys.

Kotlin
// read-only example: needs Android
class SessionManager(context: Context) {
    private val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)

    val isLoggedIn: Boolean get() = prefs.getString("token", null) != null

    fun saveLogin(userId: Long, token: String) {
        prefs.edit().putLong("user_id", userId).putString("token", token).apply()
    }

    fun logout() = prefs.edit().clear().apply()
}

Do not keep real secrets such as long-lived tokens in plain SharedPreferences; the file is readable on a rooted device and in backups. See Security on Android for encrypted storage.

The next stand-in is plain Kotlin. It models the pieces that matter: an in-memory map, an editor that stages changes, apply() that updates memory at once and writes the "file" later, commit() that writes immediately, and a change listener.

Kotlin A fake SharedPreferences (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that after apply() the new value is visible to readers at once, but the "disk" is still empty until the background write. That gap is why apply() is fast and also why a process death at the wrong moment can lose the last change. For anything new, prefer DataStore; the section below shows the one-line migration.

Migrating from SharedPreferences

You can move old settings across without writing the copy loop yourself. Pass a SharedPreferencesMigration when creating the store:

Kotlin
// read-only example: needs Android
private val Context.settingsStore by preferencesDataStore(
    name = "settings",
    produceMigrations = { context ->
        listOf(SharedPreferencesMigration(context, "legacy_settings"))
    }
)

On first access DataStore copies every key from the old file into the new store, then deletes the old file. This runs before any read or write and only once. For your own formats, implement DataMigration<T> with shouldMigrate, migrate and cleanUp.

The second TryIt models the migration plus transactional edits. The "legacy" store is a plain map, migrateOnce copies its entries (converting types) and clears it, and a failing edit throws halfway through: nothing it did before throwing is kept.

Kotlin Migration and all-or-nothing edits (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In real DataStore the draft is also written to disk using an atomic file replace, so a crash during the write leaves the previous file intact.

Session management and saving a list

Two small, very common tasks use the same storage.

Session management means "remember that the user is logged in". The wrong way is storing the password. The right way is to store a token the server gave you (and a minimal flag, such as the user ID), then clear it on logout. Keep the token in encrypted storage (see Security), not in plain SharedPreferences or DataStore text, and read it once at start-up to choose the first screen:

Kotlin
// read-only example: a session holder over DataStore
class SessionStore(private val dataStore: DataStore<Preferences>) {
    private val tokenKey = stringPreferencesKey("token")

    val isLoggedIn: Flow<Boolean> = dataStore.data.map { it[tokenKey] != null }

    suspend fun save(token: String) = dataStore.edit { it[tokenKey] = token }
    suspend fun clear() = dataStore.edit { it.remove(tokenKey) }      // logout
}

The start destination is then if (loggedIn) Home else Login, decided once, with a splash screen while the flag loads (Navigation Compose). When the server answers 401, clear the session and navigate to Login.

Saving a list. Preferences store primitives and string sets, not ArrayList<Item>. Either store a Set<String> (unordered, no duplicates) or serialize the list to JSON and store the string. Libraries such as kotlinx.serialization or Moshi do the conversion (JSON in Android). For anything beyond a handful of items that changes often, use Room instead of a big JSON blob.

Kotlin
// read-only example: a list of tags as JSON in a preference
private val tagsKey = stringPreferencesKey("tags")

suspend fun saveTags(tags: List<String>) =
    dataStore.edit { it[tagsKey] = Json.encodeToString(tags) }

val tags: Flow<List<String>> = dataStore.data.map { prefs ->
    prefs[tagsKey]?.let { Json.decodeFromString<List<String>>(it) } ?: emptyList()
}

Where DataStore fits in an app

Wrap DataStore in a repository and expose a Flow. The ViewModel turns that flow into UI state, as covered in StateFlow and collectAsStateWithLifecycle. Keep these rules in mind:

  • One DataStore instance per file, created as a top-level property or provided by dependency injection.
  • Never call runBlocking on the main thread to read a value; collect the flow or use first() from a coroutine.
  • Do not store secrets such as passwords or tokens in plain DataStore; the file is readable on a rooted device and in backups. Use Keystore-backed encryption for credentials.
  • DataStore is not multi-process safe by default; use the multi-process variant if a service in another process needs it.
flowchart LR
    UI["Settings screen"] -->|"event: toggle dark mode"| VM["ViewModel"]
    VM -->|"suspend edit { }"| DS[("DataStore file")]
    DS -->|"Flow of snapshots"| REPO["SettingsRepository"]
    REPO --> VM
    VM -->|"UiState"| UI

A write goes down into the file; every change comes back up as a new snapshot on the flow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Preferences DataStore return from data when a key was never written?

    prefs[KEY] is nullable. A missing key gives null and the usual idiom is prefs[KEY] ?: default inside the map operator.
  2. 2. Two coroutines call edit { prefs[COUNT] = (prefs[COUNT] ?: 0) + 1 } at the same time. What is the result?

    DataStore runs edits one after another and each one sees the result of the previous one, so a read-modify-write inside the block is safe.
  3. 3. When is Proto DataStore a better fit than Preferences DataStore?

    Proto DataStore stores one typed object with defaults and a serializer, so keys cannot be misspelled and types cannot be mixed up. Large or queryable data belongs in Room.
  4. 4. What happens if the lambda passed to edit throws an exception?

    An edit is transactional. The new snapshot is only committed if the block completes, so a failure leaves the previous data untouched.
  5. 5. How do you move existing SharedPreferences data into DataStore?

    SharedPreferencesMigration copies the keys across before the first read or write and then removes the old file.

Summary

  • DataStore replaces SharedPreferences with Flow-based reads and suspend, transactional writes.
  • Preferences DataStore is untyped-schema key-value with typed keys; Proto DataStore stores one immutable, serializable object.
  • Create exactly one instance per file and handle IOException in the read flow by falling back to defaults.
  • Do read-modify-write inside edit or updateData; edits are serialized and all-or-nothing.
  • Use SharedPreferencesMigration to move legacy data; use Room for large or relational data.
  • The DataStore code is read-only here; the TryIt blocks are stand-ins for typed keys, flows and transactional edits.

Next: Files, Scoped Storage and Media