What was wrong with SharedPreferences that Jetpack DataStore was built to fix, and what does DataStore guarantee instead?
answer
- synchronous API, main-thread disk I/O
- apply() reports no failure
- state that never reached disk
- Flow reads, suspending transactional writes
basics
~20 sSharedPreferences 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.
solid answer
~40 sThe DataStore source itself lists what it fixes. `SharedPreferences` is synchronous, so reads and `commit()` tend to run on the main thread and trip StrictMode. `apply()` returns at once but reports no failure, and the DataStore authors note it can still block the UI thread on `fsync()`; `commit()` only returns a boolean. Its in-memory map can hand back values that never reached disk, a read-modify-write has no transaction, and parse errors surface as runtime exceptions. DataStore replaces this with `data: Flow<T>`, which emits only durably persisted state, and `updateData` (or `edit` for Preferences DataStore), a suspending, atomic read-modify-write that is serialized with every other write, returns once the data is on disk and throws an `IOException` when the write fails.
go deeper
Recall three SharedPreferences pain points, synchronous reads, silent apply() failures and no transactions, and the two DataStore members, data and updateData.
Explain why reading a Flow of persisted state and writing through one serialized transaction removes the lost-update and unpersisted-read problems.
Show you know DataStore's limits as well: whole-file rewrites, small data only, and an exception path you now have to handle in data and updateData.
Frame the move as removing a class of main-thread stalls and lost writes, and say which data stays out of DataStore entirely: large, relational or secret.
## The short version **Jetpack DataStore** is the coroutine and Flow based replacement for `SharedPreferences`. The question is asked so often because the answer shows whether a candidate understands threading, durability and transactions on Android, not just a new API name. A good answer names the concrete defects and then the guarantee DataStore gives for each one. ## What SharedPreferences gets wrong The documentation comment on the `DataStore` interface lists the design shortcomings it addresses. In plain terms: - **A synchronous API.** `getString`, `getInt` and friends return immediately, and the first read waits for the whole XML file to load. Called from the main thread, that is disk I/O on the UI thread, which StrictMode reports. - **`apply()` hides failures.** It updates the in-memory map and schedules the disk write, but it returns nothing, so a failed write is invisible to the caller. - **`apply()` is not free either.** The DataStore authors note that `apply()` can still block the UI thread on `fsync()` when the framework waits for pending writes to finish. - **`commit()` is blocking and thin on detail.** It writes synchronously and only returns `true` or `false`. - **Not durable.** Reads come from an in-memory map that may hold values not yet persisted, so the app can act on state that a crash would lose. - **No transactions.** Reading a counter and writing it back is two separate calls; two threads doing it at once can lose an update. - **Parse errors become runtime exceptions**, and the API exposes mutable references to its internal state. ## What DataStore guarantees instead The `DataStore<T>` interface has two members that carry the whole contract: - `val data: Flow<T>` emits the latest **durably persisted** value. If reading the file fails, the Flow throws (an `IOException`), and collecting again retries the read. - `suspend fun updateData(transform: suspend (T) -> T): T` runs an **atomic read-modify-write**. All updates are serialized, the transform receives the current value, and the call returns only after the new value has been written to disk, after which `data` reflects it. If the transform or the write fails, the transaction is aborted and the exception reaches the caller. | Concern | SharedPreferences | DataStore | |---|---|---| | Threading | Synchronous getters and `commit()` | Suspending writes, Flow reads off the main thread | | Write errors | `apply()` silent, `commit()` a boolean | `updateData` / `edit` throw `IOException` | | Durability | Reads may return unpersisted values | `data` emits only persisted values | | Read-modify-write | Two calls, no transaction | One serialized transaction | | Change notification | A listener callback | Collect the `data` Flow | Preferences DataStore's `edit { }` is a thin wrapper over `updateData` that hands you a `MutablePreferences` copy, so it has the same guarantees. ## Two flavours, one engine 1. **Preferences DataStore** stores key-value pairs under typed keys such as `intPreferencesKey("font_size")`. It has no schema and no compile-time type safety, and it is the natural target when leaving `SharedPreferences`. 2. **Typed DataStore** (Proto DataStore, or a JSON-backed one) stores one immutable object through a `Serializer<T>` you provide, which gives you a schema and type safety. Both write the whole value on every update into a file under `files/datastore/`. ## Where DataStore is not the answer DataStore is meant for **small datasets**. It does not support partial updates or referential integrity: change one field and the whole object is serialized again. The Android guide points to Room for large or complex datasets, and secrets belong to the secure storage material, not to a plain DataStore file. ## A worked example Take a reading app that stores the reader's font size. With `SharedPreferences`, the settings screen calls `prefs.edit().putInt("font_size", 18).apply()` and moves on. If the write fails, nobody knows; if two screens increment the size at once, one change can vanish; and the reader view reads the value synchronously, on whatever thread it happens to be on. With DataStore, the settings screen calls a suspending `edit { it[FONT_SIZE] = 18 }` from a coroutine. The call returns only after the value is on disk, and it throws if the write fails, so the screen can show an error. The reader view collects `data.map { it[FONT_SIZE] ?: 16 }` and simply receives the new size when it is persisted. No listener registration, no main-thread read, no lost update. ## How to answer in an interview 1. Name two or three concrete `SharedPreferences` defects: synchronous reads, `apply()` hiding failures, no transactions. 2. State the DataStore contract: `data` as a Flow of persisted state, `updateData` as a serialized, durable read-modify-write. 3. Mention the two flavours and that DataStore is for small data, not a database.
- Is DataStore a good fit for a few thousand bookmarks with tags?No. DataStore rewrites the whole value on every update and supports neither partial updates nor referential integrity, so cost grows with the data and queries are impossible. The Android guide recommends Room for large or complex datasets; DataStore suits small settings and a compact typed object.
- Why does DataStore require the stored type to be immutable?`data` hands out the cached object, so mutating it would change what other readers see without any write or notification. As a safeguard, `updateData` hashes the value it passes to your transform and throws an `IllegalStateException` ("Data in DataStore was mutated...") when the transform changed that value in place instead of returning a new one. Use immutable data classes or protobuf messages.
SharedPreferences is a notepad you scribble on and hope someone files later; DataStore is a clerk who takes one change form at a time, files it, and only then says done.
- DataStore is just a coroutine wrapper around the same SharedPreferences XML file.
- apply() is fully asynchronous, so it can never block the main thread.
- DataStore keeps its data in a SQLite database, like Room.
- commit() and apply() both throw an exception when the disk write fails.
- DataStore supports partial updates, so large datasets are fine there.