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.

What was checked, and how: read this first
Checked in the docs (one web search, summaries only): the pattern of a private 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 / rememberSaveableViewModel
Best forSmall, purely visual state (a text field draft, a scroll position)Screen state and the logic that changes it
Survives rotationremember: no. rememberSaveable: yesYes (docs)
Can run logic and call the data layerAwkwardYes (Chapter 3 adds coroutines)
Testable without a screenNoYes (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

// app/build.gradle.kts (dependencies block); versions are placeholders implementation("androidx.lifecycle:lifecycle-viewmodel-compose:<version>") implementation("androidx.lifecycle:lifecycle-runtime-compose:<version>")

(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:

data class NotesUiState( val notes: List<String> = emptyList(), val isLoading: Boolean = false, val userMessage: String? = null )

The ViewModel

import androidx.lifecycle.ViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update class NotesViewModel : ViewModel() { // Private and writable inside the ViewModel only... private val _uiState = MutableStateFlow(NotesUiState(isLoading = true)) // ...exposed to the UI as read-only val uiState: StateFlow<NotesUiState> = _uiState.asStateFlow() init { loadNotes() } private fun loadNotes() { // Placeholder data: Chapters 3 to 7 replace this with real loading _uiState.update { it.copy(notes = listOf("Buy milk", "Call Ada"), isLoading = false) } } fun addNote(text: String) { if (text.isBlank()) { _uiState.update { it.copy(userMessage = "A note cannot be empty") } return } _uiState.update { it.copy(notes = it.notes + text) } } fun messageShown() { _uiState.update { it.copy(userMessage = null) } } }
  • Private writable, public read-only. (docs) The _uiState / uiState pair is the recommended shape: only the ViewModel can change the state, and the UI can only read it.
  • update replaces 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. addNote and messageShown are 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, Context and Resources references.
  • The data is fake for now. loadNotes sets 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

import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel @Composable fun NotesRoute(viewModel: NotesViewModel = viewModel()) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() NotesScreen( state = uiState, onAddNote = viewModel::addNote, onMessageShown = viewModel::messageShown ) }

(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.

import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp
@Composable fun NotesScreen( state: NotesUiState, onAddNote: (String) -> Unit, onMessageShown: () -> Unit ) { val snackbarHostState = remember { SnackbarHostState() } // Show the message once, then tell the ViewModel it has been shown LaunchedEffect(state.userMessage) { state.userMessage?.let { message -> snackbarHostState.showSnackbar(message) onMessageShown() } } Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { padding -> Column(modifier = Modifier.padding(padding).padding(16.dp)) { var draft by rememberSaveable { mutableStateOf("") } Row { OutlinedTextField(value = draft, onValueChange = { draft = it }, label = { Text("New note") }) Button(onClick = { onAddNote(draft); draft = "" }) { Text("Add") } } if (state.isLoading) { Text("Loading...") } else { LazyColumn { items(state.notes) { note -> Text(note) } } } } } }
// MainActivity: setContent { ComposeHelloTheme { NotesRoute() } }

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.

// The old way (Android Development: Architecture & Data 2) private val _notes = MutableLiveData<List<String>>() val notes: LiveData<List<String>> = _notes // In Compose you would call notes.observeAsState(); new code uses StateFlow instead
Compared with the Classic UI course
Android Development: Architecture & Data 2 covers the ViewModel lifecycle, LiveData, StateFlow and UI state patterns. The ViewModel here is the same idea. What changes is how the UI reads it: a composable collects with collectAsStateWithLifecycle(), and no observe() call, no lifecycleOwner and no view binding are needed.

Try It Yourself

Exercise 1

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.

๐Ÿ“„ View solution
Exercise 2

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.

๐Ÿ“„ View solution
Exercise 3

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.

๐Ÿ“„ View solution
Not Yet Verified
Checked in the docs (one web search, summaries only): private 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).
Coming up
Chapter 3 adds coroutines: how 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.