ViewModel and StateFlow
Android Development with Compose: Architecture & Data
Course 5 ยท Chapter 2 ยท The State Holder
Chapter 1 described a screen as a function from UI state to pixels, with events going back up. This chapter builds the thing in the middle: a ViewModel that holds the state, changes it when events arrive, and publishes it as a StateFlow for Compose to collect.
MutableStateFlow exposed as a read-only StateFlow with asStateFlow(); getting the ViewModel in a composable with viewModel() and reading it with collectAsStateWithLifecycle();
collection starting at the STARTED lifecycle state by default and stopping below it, adjustable with minActiveState; and ViewModels surviving configuration changes such as rotation. General knowledge, not checked: the Gradle artifact names, the exact import paths, the Snackbar code, the LiveData comparison, and the process-death note.
One discrepancy the docs did not explain: the Lifecycle release notes say the collectAsStateWithLifecycle() extensions arrived in version 2.6.0, while the current API reference marks them "Added in 2.10.0", so this chapter does not name a version. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.
What a ViewModel Is For
(docs) A ViewModel is the UI layer's state holder. It lives longer than any one composition: it persists across configuration changes such as screen rotation, so the new Activity instance gets the same state back instead of starting again. That is the fix for the "state lost on rotation" problem from Chapter 1.
remember / rememberSaveable | ViewModel | |
|---|---|---|
| Best for | Small, purely visual state (a text field draft, a scroll position) | Screen state and the logic that changes it |
| Survives rotation | remember: no. rememberSaveable: yes | Yes (docs) |
| Can run logic and call the data layer | Awkward | Yes (Chapter 3 adds coroutines) |
| Testable without a screen | No | Yes (it is a plain class) |
(general knowledge) A ViewModel does not survive the whole process being killed by the system. If a value must survive that too, the ViewModel can use a SavedStateHandle; this course mostly relies on Room and DataStore (Chapters 4 and 8) for anything that must last.
Setup
(general knowledge) These are the two artifacts that provide viewModel() and collectAsStateWithLifecycle(). A new project from the current Android Studio template may already include some of them; check your version catalog before adding duplicates, and take current versions from the docs or the IDE's suggestions.
The UI State
This chapter uses the data-class form from Chapter 1, with a field for a one-off message:
The ViewModel
- Private writable, public read-only. (docs) The
_uiState/uiStatepair is the recommended shape: only the ViewModel can change the state, and the UI can only read it. updatereplaces the whole state from the old one (general knowledge), so two quick changes cannot overwrite each other with stale copies the way_uiState.value = ...built from an earlier read can.- Events are plain function calls.
addNoteandmessageShownare the events flowing up from Chapter 1's diagram. - No
Context, no composables, no Activity. (docs) The recommendations say to keep ViewModels free of Activity,Contextand Resources references. - The data is fake for now.
loadNotessets placeholder notes; Chapters 3 to 7 replace it with real loading. The ViewModel builds nothing else itself, which Chapter 9 (Manual Dependency Injection) will tidy up.
Collecting the State in Compose
(docs) collectAsStateWithLifecycle() turns the StateFlow into Compose State, and only collects while the lifecycle is at least STARTED by default, so nothing is collected while the app is in the background. by unwraps the state so you can write uiState instead of uiState.value.
Two composables, one job each. NotesRoute is the stateful part: it knows about the ViewModel. NotesScreen is stateless, takes only state and callbacks, and stays previewable exactly as in Chapter 1. Keep viewModel() at the top of a screen, and pass plain values down.
One-Off Messages Without One-Off Events
(docs) The docs advise against sending one-off events from the ViewModel to the UI: process the event in the ViewModel and show the result by updating state. That is what userMessage does. The ViewModel sets the message; the screen shows it once and calls onMessageShown(), which sets it back to null. After a rotation
the state still says what to show, so nothing is lost or shown twice by accident.
(general knowledge) The exact Snackbar and LaunchedEffect handling above is one way to do it; the docs' own samples may differ in detail.
A Note on LiveData
(general knowledge) Older code publishes state with LiveData. It still works, and Compose can read it with observeAsState(), but it belongs to the View era. New code uses StateFlow, as the docs' recommendation of a StateFlow named uiState says.
collectAsStateWithLifecycle(), and no observe() call, no lifecycleOwner and no view binding are needed.
Try It Yourself
Build NotesViewModel, NotesRoute and NotesScreen, run the app, add a note, then rotate the emulator. Report whether the notes survived and what the Chapter 1 screen (with plain remember) would have done.
Add a removeNote(note: String) function to the ViewModel and a button next to each note that calls it. Explain why the ViewModel exposes StateFlow and not MutableStateFlow.
Put a counter in a remember { mutableStateOf(0) } in the screen and a second counter in the ViewModel's state. Increase both, rotate, and report which survived. Then say which one you would use for a text field draft and which for the list of notes.
MutableStateFlow exposed as StateFlow via asStateFlow(); viewModel() and collectAsStateWithLifecycle(); collection from STARTED, adjustable with minActiveState; ViewModels persisting across configuration changes; no Activity, Context or Resources in a ViewModel; no one-off events from the ViewModel to the UI.General knowledge, not checked: the Gradle artifact names; the import paths; the
update remark; the Snackbar and LaunchedEffect code; process death and SavedStateHandle; the LiveData comparison and observeAsState().Docs discrepancy, unresolved:
collectAsStateWithLifecycle() is said to be added in 2.6.0 in the release notes but "Added in 2.10.0" in the API reference; no version is claimed here.Not verified: every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: ViewModel overview (developer.android.com), collectAsStateWithLifecycle API reference (developer.android.com), Recommendations for Android architecture (developer.android.com), Kotlin coroutines with lifecycle-aware components (developer.android.com), Lifecycle releases (developer.android.com).
viewModelScope lets the ViewModel load data without freezing the screen, what the dispatchers do, and how a Flow from the data layer feeds this same state.