For over 12 years, Android developers relied on SharedPreferences to store small key-value pairs (user tokens, dark mode settings, notification flags). However, SharedPreferences had fundamental design flaws: synchronous UI-thread disk reads, no signal for runtime parsing errors, and susceptibility to crashes caused by unfinished transactions. In modern Android, Google introduced Jetpack DataStore to replace SharedPreferences.
| Dimension | Legacy SharedPreferences | Jetpack DataStore (Preferences) |
|---|---|---|
| Threading & Async API | Synchronous reads block the main thread; apply() blocks UI during onStop() |
100% Asynchronous built upon Kotlin Coroutines & Flow |
| Error Handling | Parsing errors throw uncaught runtime exceptions | Built-in IOException catch handlers and transactional error recovery |
| Data Safety | Susceptible to file corruption during unexpected crashes | ACID transactional guarantees; writes to temporary files before atomic rename |
| Reactivity | Fragile OnSharedPreferenceChangeListener easily garbage collected |
Reactive Kotlin Flow streams that update UI instantly |
import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
// Top-level property delegate (singleton across app)
val Context.dataStore by preferencesDataStore(name = "user_settings")
class UserPreferencesRepository(private val context: Context) {
private val KEY_DARK_MODE = booleanPreferencesKey("dark_mode_enabled")
private val KEY_AUTH_TOKEN = stringPreferencesKey("auth_token")
// 1. Read values reactively as a Flow
val isDarkMode: Flow<Boolean> = context.dataStore.data.map { preferences ->
preferences[KEY_DARK_MODE] ?: false // Default to false if not set
}
// 2. Write values asynchronously using Coroutines
suspend fun setDarkMode(enabled: Boolean) {
context.dataStore.edit { preferences ->
preferences[KEY_DARK_MODE] = enabled
}
}
suspend fun saveAuthToken(token: String) {
context.dataStore.edit { preferences ->
preferences[KEY_AUTH_TOKEN] = token
}
}
}
Broaden your foundational and advanced Android application development skills across our curriculum:
Compare key-value preferences with relational database tables.
Read DataStore preferences reactively via Kotlin Flow.
Secure preferences with hardware KeyStore encryption keys.
Persist user dark theme preferences in Jetpack DataStore.