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.
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?
| DataStore | Room | |
|---|---|---|
| Fits | A few small values: settings, flags, a last-used choice (general knowledge) | Lists of records, queries, relationships (Chapter 4) |
| Shape | Keys and values (Preferences) or one typed object (Proto) (docs) | Tables and rows |
| Reading | A Flow (docs) | A Flow from a DAO |
| Queries | None: you read the whole thing | SQL |
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
(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
- 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 noapply()orcommit();editis a suspend function, so call it from a coroutine. - A default for "never set". (general knowledge) A missing key reads as
null;?: trueis the default. - The
catch. (general knowledge) Reading can fail with anIOExceptionif 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
DataStoreor key objects directly.
Wiring It Into the App
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
- (docs) A
SharedPreferencesMigrationgoes inproduceMigrations; 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.
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
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.
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.
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.
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).