Why use DataStore instead of SharedPreferences, and what mistakes should you avoid?
AndroidMid-level
In shortDataStore reads through a Flow and writes in atomic, asynchronous transactions with error reporting, instead of SharedPreferences' synchronous first load and fire-and-forget apply. Use exactly one instance per file, never block the main thread on it, and do read-modify-write inside edit or updateData.
Model answer
SharedPreferences’ problems: the first access loads the whole file synchronously on the calling thread (often the main thread), apply() writes later and swallows failures, commit() blocks, and concurrent read-modify-write sequences can overwrite each other.
DataStore: data is a Flow that emits the current value and changes; edit { } (Preferences) or updateData { } (typed) runs serialized, atomic transactions on a background dispatcher and throws on failure. Preferences DataStore stores key-value pairs; typed DataStore (Proto or kotlinx.serialization) stores one object with a schema and defaults.
Mistakes to avoid:
- More than one instance per file: it throws
IllegalStateException. Use a top-levelpreferencesDataStoredelegate or a Hilt singleton. - Blocking the main thread with
runBlocking { data.first() }at startup. Read asynchronously, start with defaults or keep the splash screen until the value arrives. - Read outside, write inside:
val x = data.first(); edit { it[K] = x + 1 }loses concurrent updates; read from the lambda’s argument instead. - Ignoring corruption: add a
ReplaceFileCorruptionHandlerandcatchIOExceptions ondata. - Using it for big data: lists and queries belong in Room.
Migration: SharedPreferencesMigration copies old values on the first read.
What they're looking for
The concrete problems with SharedPreferences, the Flow and transaction model, Preferences vs typed DataStore, the single-instance rule, migration, and the common mistakes.
Common mistakes
- runBlocking { data.first() } on the main thread.
- Creating a DataStore per class or per call.
- Reading outside edit and writing inside it.
More android questions
- How do you make sure background work in a mobile app stops when the user leaves the screen?Mid-level
- What's the difference between a configuration change and process death on Android, and what survives each?Mid-level
- How would you modularize a large Android app, and how do you keep builds fast?Senior
- How do you store an auth token securely on Android?Mid-level