skip to content

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%

answer

  1. schema and type safety
  2. defaultValue, readFrom, writeTo
  3. immutable type, copy on update
  4. serialized read-modify-write
  5. first() for one snapshot

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.

solid answer

~40 s

Preferences DataStore is schemaless: string-named keys, no compile-time types. A typed DataStore stores one immutable object, a protobuf message or a `@Serializable` data class, through a `Serializer<T>` with `defaultValue` (used when no file exists), `readFrom` (throw `CorruptionException` on bad bytes) and `writeTo`. Pick it for a user profile with nested fields that change together. `updateData { it.copy(...) }` is an atomic read-modify-write: updates are serialized, the transform gets the current persisted value, and the call returns the new value after it is on disk. In DataStore 1.2, calling `updateData` inside another `updateData` on the same instance throws `IllegalStateException`. For a one-off read in a coroutine, `data.first()` returns one snapshot; never layer your own cache on top.

code

kotlin · 44 lines
kotlin
import android.content.Context
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.DataStore
import androidx.datastore.core.Serializer
import androidx.datastore.dataStore
import java.io.InputStream
import java.io.OutputStream
import kotlinx.coroutines.flow.first
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json

@Serializable
data class UserProfile(
    val displayName: String = "",
    val dailyGoalMinutes: Int = 20,
    val finishedBooks: List<String> = emptyList(),
)

object UserProfileSerializer : Serializer<UserProfile> {
    override val defaultValue: UserProfile = UserProfile()

    override suspend fun readFrom(input: InputStream): UserProfile =
        try {
            Json.decodeFromString(UserProfile.serializer(), input.readBytes().decodeToString())
        } catch (e: SerializationException) {
            throw CorruptionException("Unable to read UserProfile", 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)

suspend fun markFinished(context: Context, bookId: String): UserProfile =
    context.profileStore.updateData { profile ->
        profile.copy(finishedBooks = profile.finishedBooks + bookId)
    }

suspend fun dailyGoal(context: Context): Int =
    context.profileStore.data.first().dailyGoalMinutes

go deeper

for a junior

Recall that typed DataStore needs a Serializer with defaultValue, readFrom and writeTo, and that you update it by returning a copy from updateData.

for a middle

Explain updateData's mechanics: serialized queue, current value in, new immutable value out, return after the durable write, and why data.first() is the one-shot read.

for a senior

Discuss what breaks: a transform that mutates its input tripping the hash check, nested updateData throwing, slow transforms blocking every writer, and runBlocking at startup.

for a principal

Weigh Proto against a JSON-backed store and Preferences for the team: codegen cost, schema evolution, and when a structured object justifies a Serializer.

## Two flavours, one engine Jetpack DataStore comes in two forms that share the same core: a `DataStore<T>` with a `data` Flow and a suspending `updateData`. | | Preferences DataStore | Typed DataStore | |---|---|---| | Stored value | `Preferences`, a map of typed keys | One object of your type `T` | | Schema | None; keys are strings | A protobuf message or a serializable class | | Type safety | Only through the key's type, checked at runtime | Compile-time, through `T` | | Write API | `edit { prefs[KEY] = v }` | `updateData { it.copy(...) }` | | Factory | `preferencesDataStore(name)` | `dataStore(fileName, serializer)` | Choose **typed DataStore** when the value is a structured object, such as a reading app's user profile with a display name, a daily goal and a list of finished books, and you want one schema, defaults in one place and fields that update together. Choose **Preferences DataStore** for a handful of flat settings or when migrating straight from `SharedPreferences`. ## Building a typed store A typed store needs a `Serializer<T>` with three members: - **`defaultValue`**: the value DataStore returns when there is **no file on disk yet**. - **`readFrom(input)`**: decodes the stream. When the bytes cannot be parsed, it must throw **`CorruptionException`**, wrapping the parser's exception, so DataStore treats it as corruption. - **`writeTo(t, output)`**: encodes the value. Closing the stream is a no-op. Both functions are `suspend`. **Proto DataStore** uses a class generated from a `.proto` file with `parseFrom` and `writeTo`; a JSON store uses kotlinx.serialization. You then declare the store once with the `dataStore(fileName = ..., serializer = ...)` delegate. `T` **must be immutable**. `data` hands out the cached object, so mutating it in place would change what every reader sees with no write behind it. As a safeguard, `updateData` hashes the value it hands to your transform and throws `IllegalStateException` ("Data in DataStore was mutated but DataStore is only compatible with Immutable types.") when the transform changed that value in place instead of returning a new one. Use `copy` on data classes or `toBuilder()` on protobuf messages. ## What updateData does `suspend fun updateData(transform: suspend (T) -> T): T` is an **atomic read-modify-write**: 1. The call is queued behind any other update on the same instance, so **all writes are serialized**. 2. DataStore reads the current persisted value and passes it to your transform. 3. Your transform returns a **new** value; it may suspend, so it can do real work. 4. If the result equals the current value, DataStore skips the disk write; otherwise it writes the whole object. 5. The call returns the new value **after** it is durably on disk, and `data` emits it. If the transform throws or the write fails, the transaction is aborted and the exception reaches the caller. Nesting `updateData` inside another `updateData` on the **same instance** throws `IllegalStateException`, because the inner call could not see the outer change; before 1.1.0-beta02 that pattern deadlocked instead. ## Reading one value with first() `data` is a Flow that never completes. For a one-off read inside a coroutine: - `data.first()` returns a single snapshot of the persisted value and stops collecting. - `collect` or `single()` would suspend indefinitely, because the Flow keeps waiting for new values. - The `DataStore` docs say not to layer a cache on top: it cannot stay consistent with other writers. Call `data.first()` again when you need the value again. A synchronous read at startup is the hard case. `runBlocking { store.data.first() }` on the main thread blocks the UI until the file is read and any migrations have run, which risks an ANR. Prefer starting an asynchronous `data.first()` early, which loads DataStore's in-memory cache so a later read is fast. ## Evolving the stored type A typed store lives across app updates, so its type must stay readable by newer versions of the app: - with **protobuf**, add new fields with new field numbers and never reuse or renumber an old one; unknown and missing fields are handled by the protobuf runtime; - with **kotlinx.serialization**, give new properties default values so old files still decode, and decide whether unknown keys should be ignored; - a change that no longer decodes old bytes surfaces as `CorruptionException` from `readFrom`, which is why the serializer must throw that type rather than its parser's own exception. ## Choosing between the two - Flat settings, few keys, migrating from `SharedPreferences`: Preferences DataStore. - One structured object with typed fields and nested lists: typed DataStore with a `Serializer`. - Large or relational data: neither, it belongs in a database.

  • Why would a team pick Proto DataStore over a JSON-backed typed store?
    Protobuf messages are immutable, compact, generated from a schema, and add or remove fields with well-defined compatibility, which the DataStore docs recommend. The cost is the protobuf Gradle plugin and generated code. A kotlinx.serialization store avoids codegen and is easy to read, but schema evolution relies on default values and the serializer's settings.
  • Can the updateData transform do slow work, such as a network call?
    It can, because the transform is a suspend function, but every other update on that store waits behind it. Keep transforms short: fetch first, then call `updateData` with a transform that only computes the new value from the current one.

updateData is a bank teller with one queue: each slip is applied to the balance left by the previous one, and you get your receipt only after the ledger is written.

  • A typed DataStore lets you mutate the object from data and save it later.
  • updateData returns before the write reaches disk, like SharedPreferences.apply().
  • Calling updateData inside updateData on the same store merges the two changes.
  • Collecting data with collect is the way to read one value.
  • Caching the first emitted value in a field keeps reads consistent.

Assumes DataStore 1.2.1; the IllegalStateException for nested updateData (previously a deadlock) and the skipped write for unchanged data both arrived during the 1.1.0 betas and release candidate.