Saving Settings with DataStore

Android Development 9 min min read Updated: Nov 16, 2026 Beginner
Saving Settings with DataStore
Beginner Topic 6 of 6

DataStore vs SharedPreferences

SharedPreferencesDataStore
APISynchronousAsynchronous with Flow and coroutines
Main thread safeNo (can freeze UI)Yes
ErrorsCan crashHandled with exceptions in Flow
Use for new codeNoYes

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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators