How to Use DataStore for Preferences in Android
Android’s DataStore provides a modern way to store small amounts of application data, such as a dark-mode choice, notification setting, language preference or whether a welcome screen has been dismissed. It is designed to replace many common SharedPreferences use cases while offering asynchronous access, Kotlin Coroutines and safer data handling.
For Australian developers building apps for users in Sydney, Melbourne, Brisbane or regional areas, reliable local storage matters when connectivity is inconsistent. A settings screen should remain responsive on a train commute, during travel through rural areas or when a user is switching between Wi-Fi and mobile data. Preferences DataStore is well suited to these lightweight, user-specific settings.
Why Preferences DataStore is useful
SharedPreferences uses synchronous read and write methods that can contribute to main-thread work, especially when an app loads settings during startup. It also lacks a straightforward way to observe changes reactively. DataStore addresses these issues by exposing preferences through a Kotlin Flow and performing file operations asynchronously.
Preferences DataStore stores values as key-value pairs. It does not require a predefined schema, which makes it convenient for boolean, string, integer, double and long settings. For example, an app can save isDarkMode, fontScale, selectedState or notificationsEnabled without creating a database table.
The API also improves consistency when multiple parts of an app update preferences. DataStore handles updates transactionally, so an edit operation reads the current values, applies a change and writes the result as one operation. This helps avoid some of the race conditions associated with manual preference management.
It is still important to use DataStore for small settings rather than large records or complex relational data. An app storing hundreds of customer orders, product listings or offline documents should consider Room or another database.
Add DataStore to an Android project
Add the Preferences DataStore dependency to the app module’s Gradle file. The version should match the current stable AndroidX release used by the project:
dependencies {
implementation("androidx.datastore:datastore-preferences:1.1.1")
}
Create a single DataStore instance at the appropriate application level. The preferencesDataStore delegate is commonly declared in a Kotlin file outside an Activity or Fragment:
import android.content.Context
import androidx.datastore.preferences.preferencesDataStore
val Context.settingsDataStore by preferencesDataStore(
name = "user_settings"
)
Using one instance for a given file is essential. Creating multiple DataStore instances for the same file can cause runtime errors and make preference updates difficult to reason about. Keep the declaration central, then inject the DataStore or repository into the components that need it.
A small project examples collection can be useful when comparing repository arrangements, lifecycle handling and Kotlin conventions. Treat external examples as reference material, then adapt the structure to your own package organisation and testing strategy.
Define keys and expose settings with Flow
Preference keys should be declared once, rather than recreated throughout the application. Typed key functions make the expected value clear:
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
object PreferenceKeys {
val DARK_MODE = booleanPreferencesKey("dark_mode")
val SELECTED_STATE = stringPreferencesKey("selected_state")
}
A repository can expose preferences as a data stream. The data property returns a Flow<Preferences>, which can be mapped into a domain model used by the user interface:
data class UserSettings(
val darkMode: Boolean = false,
val selectedState: String = "NSW"
)
class SettingsRepository(
private val context: Context
) {
val settings: Flow<UserSettings> =
context.settingsDataStore.data.map { preferences ->
UserSettings(
darkMode = preferences[PreferenceKeys.DARK_MODE] ?: false,
selectedState = preferences[PreferenceKeys.SELECTED_STATE] ?: "NSW"
)
}
}
The fallback value is important because a key may not exist the first time the app runs. Choosing a sensible default also makes the interface predictable. An Australian travel app might default to metric units and Australian English, while a shopping app could use an Australian state selection only if that behaviour is genuinely appropriate for its audience.
In a ViewModel, collect the repository’s Flow with stateIn, collectAsStateWithLifecycle or another lifecycle-aware approach. This means a Compose screen can update automatically when the user changes a setting, without manually requesting the latest value after every edit.
Write preferences safely from the interface
To change a value, call edit on the DataStore. The operation is suspendable, so it should run from a coroutine, typically in a ViewModel or repository:
suspend fun setDarkMode(context: Context, enabled: Boolean) {
context.settingsDataStore.edit { preferences ->
preferences[PreferenceKeys.DARK_MODE] = enabled
}
}
suspend fun setSelectedState(context: Context, state: String) {
context.settingsDataStore.edit { preferences ->
preferences[PreferenceKeys.SELECTED_STATE] = state
}
}
A ViewModel can expose intent-style methods to the UI:
class SettingsViewModel(
private val repository: SettingsRepository
) : ViewModel() {
val settings = repository.settings
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = UserSettings()
)
fun setDarkMode(enabled: Boolean) {
viewModelScope.launch {
repository.setDarkMode(enabled)
}
}
}
Keep file access out of Composable functions and Activities where possible. This separation makes the code easier to test and prevents lifecycle events from creating duplicate work. It also supports familiar Android architecture patterns such as a repository, ViewModel and unidirectional data flow.
When a preference must be removed, use remove with its key. For a complete reset, call clear, but make that action explicit because it will remove every value in the DataStore file. A “Reset settings” option should usually have a confirmation step, particularly in apps used by families or shared devices.
Migrate, test and protect user expectations
DataStore includes a migration path from SharedPreferences. Use SharedPreferencesMigration when an existing application is moving to DataStore, and choose the same preference file name used by the legacy implementation. Migration should be tested with realistic upgrade scenarios, including users who have never saved a particular key.
val Context.settingsDataStore by preferencesDataStore(
name = "user_settings",
produceMigrations = { context ->
listOf(
SharedPreferencesMigration(
context = context,
sharedPreferencesName = "legacy_settings"
)
)
}
)
Test default values, successful updates, resets and corrupted or unavailable storage behaviour. Android’s DataStore test utilities can help verify repository logic without relying on a full UI test. Also check process recreation: preferences should still be available after the app is closed and reopened.
For broader Android architecture patterns, an Android learning guide can provide useful background on Kotlin, lifecycle-aware collection and Jetpack components. Keep security boundaries in mind, however. Preferences DataStore is not an encrypted vault. Do not store passwords, payment details, private keys or authentication tokens there unless an appropriate secure storage layer is added.
Practical recommendations for production apps
A dependable implementation usually follows a few simple rules:
- Create one DataStore instance per preference file and keep its declaration central.
- Define typed keys in one object or file so names remain consistent.
- Expose a domain model instead of passing raw
Preferencesthroughout the UI. - Collect preference data with lifecycle-aware Kotlin Flow APIs.
- Use repositories and ViewModels to keep file operations away from Composable functions.
- Add migration tests before replacing an established SharedPreferences implementation.
- Avoid storing sensitive credentials or large application datasets in Preferences DataStore.
For an app released through the Australian market, also test settings around device language, metric units, daylight-saving changes and intermittent network access. A user in Perth may have different daylight-saving expectations from someone in Melbourne, while a regional user may spend longer periods offline. DataStore cannot solve every product decision, but it can make those decisions persist reliably on the device.
Start by moving one low-risk preference, such as a theme or notification toggle, into a repository-backed DataStore implementation. Once the Flow, coroutine handling and tests are working, migrate related settings carefully and remove the old access paths. This incremental approach keeps the change manageable while giving the app a more responsive and maintainable preferences layer.