Saving Settings with DataStore
DataStore vs SharedPreferences
| SharedPreferences | DataStore | |
|---|---|---|
| API | Synchronous | Asynchronous with Flow and coroutines |
| Main thread safe | No (can freeze UI) | Yes |
| Errors | Can crash | Handled with exceptions in Flow |
| Use for new code | No | Yes |
Use DataStore for small settings: theme, onboarding done, sort order. For lists and complex data use Room.
Setup
kotlin
implementation(libs.androidx.datastore.preferences)
A Settings Repository
kotlin
private val Context.dataStore by preferencesDataStore(name = "settings")
class SettingsRepository(private val context: Context) {
private object Keys {
val DARK_MODE = booleanPreferencesKey("dark_mode")
val USER_NAME = stringPreferencesKey("user_name")
val ONBOARDING_DONE = booleanPreferencesKey("onboarding_done")
}
val darkMode: Flow<Boolean> = context.dataStore.data
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
.map { it[Keys.DARK_MODE] ?: false }
val onboardingDone: Flow<Boolean> = context.dataStore.data
.map { it[Keys.ONBOARDING_DONE] ?: false }
suspend fun setDarkMode(enabled: Boolean) {
context.dataStore.edit { it[Keys.DARK_MODE] = enabled }
}
suspend fun setOnboardingDone() {
context.dataStore.edit { it[Keys.ONBOARDING_DONE] = true }
}
}
Use It in a ViewModel and Screen
kotlin
class SettingsViewModel(private val repo: SettingsRepository) : ViewModel() {
val darkMode = repo.darkMode.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
fun toggle(enabled: Boolean) = viewModelScope.launch { repo.setDarkMode(enabled) }
}
@Composable
fun SettingsScreen(viewModel: SettingsViewModel) {
val dark by viewModel.darkMode.collectAsStateWithLifecycle()
Row(Modifier.fillMaxWidth().padding(16.dp), horizontalArrangement = Arrangement.SpaceBetween) {
Text("Dark mode")
Switch(checked = dark, onCheckedChange = viewModel::toggle)
}
}
Security: DataStore is not encrypted. Do not store passwords or tokens in plain DataStore. Use encrypted storage and the Android Keystore, or let a credential library manage sign-in.
Tip: Create one DataStore instance per file. The
preferencesDataStore property delegate at the top level of a file does this for you.
Conclusion
DataStore saves small settings asynchronously and exposes them as a Flow, so the UI updates automatically.
Quick Summary: Define keys, read with data.map, write with edit, and collect the Flow in a ViewModel.

