Storing Preferences (DataStore)
DataStore over SharedPreferences
`SharedPreferences` is synchronous and error-prone. `DataStore` is the modern replacement: it is async, transactional, and exposes settings as a `Flow`. Perfect for things like theme choice or onboarding flags.
๐ Explanation
`preferencesDataStore` creates a single, type-safe key/value store backed by a coroutine `Flow`. Reads never block the main thread and automatically re-emit when a value changes. Writes go through `edit { }`, which is transactional โ concurrent updates are serialized safely. This makes DataStore a drop-in, leak-free upgrade over `SharedPreferences` for app settings.
Note: Code execution is not available for Android/Kotlin in the browser. Use Android Studio to run and test the app.
import androidx.datastore.core.DataStoreimport androidx.datastore.preferences.core.*import androidx.datastore.preferences.preferencesDataStoreimport android.content.Contextimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.map// Define a single DataStore instance for the appval Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")class SettingsRepository(private val context: Context) {private object Keys {val DARK_MODE = booleanPreferencesKey("dark_mode")}// Read: exposed as a Flow that emits on every writeval darkMode: Flow<Boolean> = context.dataStore.data.map { prefs -> prefs[Keys.DARK_MODE] ?: false }// Write: suspending + transactionalsuspend fun setDarkMode(enabled: Boolean) {context.dataStore.edit { prefs ->prefs[Keys.DARK_MODE] = enabled}}}