The List Screen
Personal Catalogue: Android (Kotlin & Compose)
Course 1 ยท Chapter 4 ยท ViewModel, LazyColumn and Filter Chips
The database exists but nothing shows it. This chapter builds the app's home screen: a scrolling list of every item, newest first, with a row of chips to filter by type (Book, CD, DVD, Blu-ray), and a friendly message when there is nothing to show. It is also where the course's screen pattern is set, and every later screen repeats it: a ViewModel holds the state, a stateful composable collects it, and a stateless composable draws it.
FilterChip, so its parameters are from my memory and are the likeliest place for a compile error. Check the Material 3 component page if your IDE complains.
The Pattern: Three Parts per Screen
| Part | Android | Web catalogue equivalent |
|---|---|---|
| State holder | ListViewModel exposing a StateFlow<ListUiState> | The Django view (gathers the data), or a React hook |
| Stateful composable | ListScreen: gets the view model, collects the state | A container component |
| Stateless composable | ListContent: takes plain values and callbacks, draws them | The template, or a presentational component |
The split pays off twice. The stateless composable can be previewed and tested with made-up data, and the view model survives screen rotation, so the selected filter does not reset when the phone turns.
The UI State and the ViewModel
Describe everything the screen needs in one immutable class. The view model combines three flows (the items, the types, and which type is selected) into it. Google's recommended way to turn that into a
StateFlow is stateIn with SharingStarted.WhileSubscribed(5000): the flow stays active for five seconds after the screen disappears, so a rotation does not restart the work.
Two details. ensureSeeded() (Chapter 3) runs when the view model is created; the type chips appear as soon as the insert finishes, because itemTypes is a Flow. And
the filtering is done in memory on the already-loaded list: for a personal collection of a few thousand items that is simple and fast. Chapter 8 moves search into the database, where it belongs once there are
several conditions.
The Stateful Screen
The stateful composable gets the view model from Hilt (hiltViewModel(), from the hilt-navigation-compose dependency you added in Chapter 3) and turns the StateFlow
into Compose state. collectAsStateWithLifecycle() is Google's recommended way to do that: it only collects while the screen is at least started, so a backgrounded app does no
needless work. It needs the androidx.lifecycle:lifecycle-runtime-compose artifact; if your project does not have it, add it to the version catalog like the others.
The Stateless Content
Now the drawing. ListContent receives plain values and lambdas, and knows nothing about view models. This is state hoisting: the state lives higher up, and the composable
below it only displays state and reports events (Chapter 6 returns to this idea for the form). The pieces are a Scaffold with a top bar and a "+" button, a row of filter chips, and either a
LazyColumn or an empty-state message.
Points worth knowing. items(state.items, key = { it.item.id }) gives each row a stable key: Compose uses it to keep a row's identity when the list changes (an item
deleted from the middle, say) instead of treating every following row as new. LazyColumn only composes the rows that are on screen, which is why it is the right choice for a list of unknown
length, unlike a plain Column that would build every row up front. The two empty messages come from totalCount: "Nothing of this type yet" appears when a filter hides everything, "Your catalogue
is empty" only when there really is nothing. The icon needs Icons.Filled.Add, which lives in the core icon set; the larger extended set is not needed for this app.
Showing It
Replace the body of CatalogueApp from Chapter 1 so that it displays the list. (Chapter 5 will replace this again with navigation.) Remove the unused imports the IDE greys out.
Run it. You should see the top bar, four chips plus "All", and the empty message. Tap the "+" button: for now it inserts a sample item, which appears immediately with no refresh code, because the list is
collecting a Flow that Room re-emits on every change. That is the whole payoff of the architecture so far.
@Query in the view replaces the view model and the flow plumbing, and a List with a segmented
Picker replaces the LazyColumn and chips. The screens look alike; the Android version has more moving parts because it keeps the state holder and the drawing apart.
Challenges
Add ListViewModel, ListScreen and ListContent, update CatalogueApp, and run it. Tap "+" three times, tap a type chip, then "All". Write down
what you see for each of the two empty messages and how you triggered each.
Change the top bar title to show the number of items currently listed, for example "My Catalogue (3)". Decide where the number should come from: the view model, or computed in
ListContent from state.items.
Rotate the emulator while a type chip is selected. Explain why the chip stays selected, and what would happen if selectedTypeId were stored with
remember { mutableStateOf(...) } inside ListContent instead. Then name the Compose function that would keep it across rotation without a view model.
Chapter 4 Quick Reference
- Screen pattern: ViewModel (state) → stateful composable (collects) → stateless composable (draws, takes values and lambdas)
combine(flowA, flowB, flowC) { ... }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial)builds theStateFlow@HiltViewModel+@Inject constructor; in a screen:hiltViewModel()val state by vm.uiState.collectAsStateWithLifecycle()(needslifecycle-runtime-compose)LazyColumn { items(list, key = { it.id }) { ... } }: only visible rows are composed; keys keep row identityFilterChip(selected, onClick, label)in aLazyRowfor the type filter;nulltype id means All- Two empty states: no items at all, and no items of the chosen type (decide with
totalCount)
collectAsStateWithLifecycle is the recommended way to collect flows in Compose and collects from the STARTED state; that the documented
pattern builds UI state with stateIn and WhileSubscribed(5000) (the five seconds covering configuration changes); that hiltViewModel() is paired with it in Google's
state-holder guide; and that a documented LazyColumn example sets a key.Not checked, from general knowledge:
FilterChip (the search found nothing on it; parameters and any opt-in annotation requirement may differ in your Material 3 version);
TopAppBar needing @OptIn(ExperimentalMaterial3Api) in some versions; Icons.Filled.Add being in the core icon set; the artifact name
lifecycle-runtime-compose; the wildcard imports resolving correctly; the combine overload for three flows; and all code, none of which was compiled.