DataStore and Preferences

Android Development with Compose: Architecture & Data

Course 5 ยท Chapter 8 ยท Remembering Settings

Room is for lists of records. For a handful of settings ("sort newest first", "dark mode", the last tab you used) there is a lighter tool: DataStore. It replaces the older SharedPreferences, and like everything else in this course it speaks coroutines and Flow.

What was checked, and how: read this first
Checked in the docs (one search, summaries only): DataStore has two implementations, Preferences DataStore (key-value) and Proto DataStore (typed objects with protocol buffers); it is built on coroutines and Flow; the Preferences API exposes data as a Flow and has no apply() or commit(); Proto uses updateData() for an atomic read-modify-write; a SharedPreferencesMigration goes in the produceMigrations parameter of the preferencesDataStore delegate, with the old key names reused so values carry over; migrations run before any data is read or edited; reading DataStore inside a migration callback deadlocks; and the release page listed 1.3.0 as the latest stable version at the time of the search (the dependency below still uses a placeholder). General knowledge, not checked: the code shown (key functions, edit usage, the catch for IOException, the delegate defined at top level), "one instance per file", the comparison with SharedPreferences, and the DataStore-or-Room advice. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.

DataStore or Room?

DataStoreRoom
FitsA few small values: settings, flags, a last-used choice (general knowledge)Lists of records, queries, relationships (Chapter 4)
ShapeKeys and values (Preferences) or one typed object (Proto) (docs)Tables and rows
ReadingA Flow (docs)A Flow from a DAO
QueriesNone: you read the whole thingSQL

And rememberSaveable (Android Development Fundamentals with Compose 4) is for state that only has to survive rotation on one screen, not forever.

Setup and Creating the DataStore

// Module build.gradle.kts (version is a placeholder) dependencies { implementation("androidx.datastore:datastore-preferences:<datastore-version>") }
import android.content.Context import androidx.datastore.preferences.preferencesDataStore // Top level, once per file name: one DataStore instance per file val Context.settingsDataStore by preferencesDataStore(name = "settings")

(general knowledge) The delegate is declared once, at the top level of a file, as an extension on Context. Creating two DataStores for the same file name is an error in the library; this declaration is what guarantees one.

A Settings Repository

import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.emptyPreferences import java.io.IOException import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map class SettingsRepository( private val dataStore: DataStore<Preferences> ) { private val newestFirstKey = booleanPreferencesKey("newest_first") // Reading: a Flow, so the UI follows changes automatically val newestFirst: Flow<Boolean> = dataStore.data .catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e } .map { prefs -> prefs[newestFirstKey] ?: true } // default when never set // Writing: a suspend function, no apply() or commit() suspend fun setNewestFirst(value: Boolean) { dataStore.edit { prefs -> prefs[newestFirstKey] = value } } }
  • Reading is a Flow. (docs) The Preferences API exposes data as a Flow, so a screen that collects it updates when the setting changes, from anywhere.
  • Writing is edit. (docs) There is no apply() or commit(); edit is a suspend function, so call it from a coroutine.
  • A default for "never set". (general knowledge) A missing key reads as null; ?: true is the default.
  • The catch. (general knowledge) Reading can fail with an IOException if the file cannot be read; this falls back to empty preferences, so defaults apply, rather than crashing.
  • It is a repository in the sense of Chapter 5: the ViewModel never touches DataStore or key objects directly.

Wiring It Into the App

class NotesApp : Application() { // ...database and notesRepository as before... val settingsRepository: SettingsRepository by lazy { SettingsRepository(settingsDataStore) // the Context extension from above } }
data class NotesUiState( val notes: List<Note> = emptyList(), val newestFirst: Boolean = true, // new val isLoading: Boolean = false, val isRefreshing: Boolean = false, val userMessage: String? = null )
class NotesViewModel( private val repository: NotesRepository, private val settings: SettingsRepository ) : ViewModel() { private val message = MutableStateFlow<String?>(null) private val isRefreshing = MutableStateFlow(false) val uiState: StateFlow<NotesUiState> = combine(repository.getNotesStream(), settings.newestFirst, message, isRefreshing) { notes, newestFirst, userMessage, refreshing -> NotesUiState( notes = if (newestFirst) notes.sortedByDescending { it.createdAt } else notes.sortedBy { it.createdAt }, newestFirst = newestFirst, isRefreshing = refreshing, userMessage = userMessage ) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = NotesUiState(isLoading = true) ) fun setNewestFirst(value: Boolean) { viewModelScope.launch { settings.setNewestFirst(value) } } // addNote, deleteNote, refresh and messageShown are as in the earlier chapters } // In the Factory: NotesViewModel(app.notesRepository, app.settingsRepository)
// In NotesScreen Row(verticalAlignment = Alignment.CenterVertically) { Text("Newest first") Switch(checked = state.newestFirst, onCheckedChange = onNewestFirstChange) }

combine with a fourth flow is the same technique as Chapters 3 and 7: when the setting changes, the state rebuilds and the list re-sorts; no other code needs to know. The route passes onNewestFirstChange = viewModel::setNewestFirst. Toggle the switch, close the app completely and reopen it: the choice is still there.

Moving Over From SharedPreferences

import androidx.datastore.migrations.SharedPreferencesMigration val Context.settingsDataStore by preferencesDataStore( name = "settings", produceMigrations = { context -> listOf(SharedPreferencesMigration(context, "old_prefs_file_name")) } )
  • (docs) A SharedPreferencesMigration goes in produceMigrations; reuse the old key names so values carry over.
  • (docs) Migrations run before any data access, so the first read waits for them to finish.
  • (docs) Do not read the DataStore inside a migration callback: it deadlocks, because DataStore returns nothing until all migrations complete.
  • (docs) Migrations should be idempotent (safe to run more than once), and if the old file ends up empty the migration tries to delete it.

This app has no old SharedPreferences file, so the snippet is for reference. (general knowledge) Older code often used it to remember small values; SharedPreferences has a synchronous API, which is one reason it was replaced.

Proto DataStore, Described

(docs) The other flavour stores a typed object defined with protocol buffers instead of loose keys, and changes it with updateData(), an atomic read-modify-write. The Proto codelab suggests a sentinel enum value such as UNSPECIFIED as the default, so a migration can tell whether a value still needs to be copied from SharedPreferences. (general knowledge) It needs a protobuf schema file and the protobuf Gradle plugin, so it is more setup; it is worth it when settings are a structured object and you want the compiler to check the types. This chapter does not build one.

Compared with the Classic UI course
Android Development: Architecture & Data 7 teaches DataStore as a replacement for SharedPreferences, covering Preferences and Proto DataStore. The ideas are identical. The Compose difference is how a setting reaches the screen: a Flow feeds the ViewModel's state, and the switch is just another part of NotesUiState.

Try It Yourself

Exercise 1

Add the dependency, settingsDataStore, SettingsRepository and the "Newest first" switch. Toggle it, kill the app, reopen it, and report whether the setting survived and whether the list re-sorted.

๐Ÿ“„ View solution
Exercise 2

Add a second setting, an integer limit on how many notes to show, using an Int key with a default. Show it with a simple control of your choice and apply it in the ViewModel. Report anything that surprised you.

๐Ÿ“„ View solution
Exercise 3

For each of these, say whether you would use rememberSaveable, a ViewModel, DataStore or Room, and why: the text typed into the new-note box; the current list of notes; the sort order; a dark-mode choice; a cache of 5,000 articles.

๐Ÿ“„ View solution
Not Yet Verified
Checked in the docs (one search, summaries only): the two DataStore flavours; coroutines and Flow; no apply() or commit(); updateData() for Proto; SharedPreferencesMigration in produceMigrations; reusing key names; migrations run before data access; the deadlock warning; idempotent migrations and old-file deletion; the UNSPECIFIED sentinel suggestion; 1.3.0 listed as latest stable.
General knowledge, not checked: the code as shown (key functions, edit, the IOException catch, the top-level delegate); one instance per file; the SharedPreferences comparison; the DataStore, Room and rememberSaveable advice; Proto setup needs.
Not verified: every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: DataStore (developer.android.com), Working with Preferences DataStore codelab (developer.android.com), Working with Proto DataStore codelab (developer.android.com), SharedPreferencesMigration API reference (developer.android.com), DataStore releases (developer.android.com).
Coming up
The next chapter, Chapter 9 (Manual Dependency Injection), looks at what has been happening all along: the app container, the hand-written factory and the objects handed to the ViewModel, and how to organise that deliberately.