DataStore & Preferences Flashcards

DATA › Storage

What is the difference between SharedPreferences.commit() and apply()?
commit() writes to disk synchronously on the calling thread and returns a Boolean success flag. apply() updates the in-memory map immediately and schedules the disk write asynchronously, returning void. Use apply() to avoid blocking the main thread.
What are the two types of DataStore and how do they differ?
Preferences DataStore stores untyped key-value pairs (like SharedPreferences, no schema, no compile-time type safety). Proto DataStore stores typed objects defined in a .proto schema, giving full compile-time type safety via generated classes.
Why is DataStore recommended over SharedPreferences?
DataStore exposes reads as a Flow and writes as suspend functions, so it never blocks the UI thread. Writes are transactional and atomic, it surfaces errors instead of swallowing them, and it integrates with Kotlin coroutines and structured concurrency.
How do you read and write with Preferences DataStore?
Read via dataStore.data, a Flow<Preferences>, mapping keys created with helpers like stringPreferencesKey() or intPreferencesKey(). Write via the suspend dataStore.edit { } block, which runs as a single atomic transaction.
How do you migrate existing SharedPreferences into DataStore?
Pass SharedPreferencesMigration(context, "prefs_name") in the migrations list when building the DataStore (e.g. via preferencesDataStore(name, produceMigrations)). On first read it copies the values across, then by default deletes the original SharedPreferences file.
Is EncryptedSharedPreferences still recommended in 2026?
No. EncryptedSharedPreferences (androidx.security:security-crypto) is deprecated. Google now recommends storing only data you can re-fetch, relying on file/full-disk encryption, and using the Jetpack Security state in conjunction with the Keystore, or other maintained crypto libraries for secrets.
What happens if a DataStore file is corrupted, and how do you handle it?
Reading throws a CorruptionException (surfaced through the data Flow). You provide a ReplaceFileCorruptionHandler when creating the DataStore to recover by replacing the bad file with a default value instead of crashing.
Why must you have only one DataStore instance per file per process?
DataStore enforces in-process consistency and serializes writes through a single instance. Creating a second instance for the same file throws an IllegalStateException, because two instances would break read-after-write consistency and atomicity.
Both apply() and commit() write to disk eventually, so why prefer apply()?
Both update the in-memory cache atomically, so reads see changes immediately either way. apply() moves the actual disk I/O off the calling thread, avoiding jank, whereas commit() performs disk I/O inline and can stall the main thread (especially with frequent or large writes).

Back to DataStore & Preferences