Interview frequency: …
Short answer
Because DataStore is completely thread-safe, relies on Kotlin coroutines and Flow, and handles errors safely without blocking the UI or causing ANR errors.
Explanation
SharedPreferences relied on read and write operations that could block the UI thread (through apply or synchronous commit) causing ANR, in addition to having no unified mechanism to report disk write errors. DataStore provides fully asynchronous handling that guarantees atomic data consistency and supports two kinds: Preferences DataStore and Proto DataStore.
Code example
// Safely read the settings flow:
val IS_DARK_MODE = booleanPreferencesKey("is_dark_mode")
val isDarkModeFlow: Flow<Boolean> = context.dataStore.data
.map { preferences -> preferences[IS_DARK_MODE] ?: false }
// Save the setting asynchronously:
suspend fun setDarkMode(enabled: Boolean) {
context.dataStore.edit { preferences ->
preferences[IS_DARK_MODE] = enabled
}
}Common mistakes
- Trying to read a DataStore value synchronously by blocking the thread (runBlocking), which reproduces the same problems as SharedPreferences.