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.

What was run, and what was not
Nothing was compiled or run (no Android Studio here). My search confirmed the state-collection pattern in Google's documentation but found nothing on Material 3's 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

PartAndroidWeb catalogue equivalent
State holderListViewModel exposing a StateFlow<ListUiState>The Django view (gathers the data), or a React hook
Stateful composableListScreen: gets the view model, collects the stateA container component
Stateless composableListContent: takes plain values and callbacks, draws themThe 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.

package com.example.catalogue.ui.list import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.catalogue.data.CatalogueRepository import com.example.catalogue.data.Item import com.example.catalogue.data.ItemType import com.example.catalogue.data.ItemWithDetails import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch data class ListUiState( val isLoading: Boolean = true, val types: List<ItemType> = emptyList(), val selectedTypeId: Long? = null, // null means "All" val items: List<ItemWithDetails> = emptyList(), // already filtered val totalCount: Int = 0 // before filtering, to choose the empty message ) @HiltViewModel class ListViewModel @Inject constructor( private val repository: CatalogueRepository ) : ViewModel() { private val selectedTypeId = MutableStateFlow<Long?>(null) val uiState: StateFlow<ListUiState> = combine( repository.items, repository.itemTypes, selectedTypeId ) { items, types, selected -> ListUiState( isLoading = false, types = types, selectedTypeId = selected, items = if (selected == null) items else items.filter { it.item.itemTypeId == selected }, totalCount = items.size ) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = ListUiState() ) init { viewModelScope.launch { repository.ensureSeeded() } } fun onTypeSelected(typeId: Long?) { selectedTypeId.value = typeId } // TEMPORARY: lets you see rows before the form exists (Chapter 6 removes this). fun addSampleItem() { viewModelScope.launch { val type = uiState.value.types.firstOrNull() ?: return@launch repository.saveItem( Item(title = "Sample item", creator = "Sample creator", itemTypeId = type.id), tagIds = emptySet() ) } } }

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.

package com.example.catalogue.ui.list import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle @Composable fun ListScreen( onAddClick: () -> Unit, onItemClick: (Long) -> Unit, viewModel: ListViewModel = hiltViewModel() ) { val state by viewModel.uiState.collectAsStateWithLifecycle() ListContent( state = state, onTypeSelected = viewModel::onTypeSelected, onAddClick = viewModel::addSampleItem, // TEMPORARY; Chapter 6 uses onAddClick onItemClick = onItemClick ) }

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.

package com.example.catalogue.ui.list import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.clickable import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.example.catalogue.data.ItemWithDetails @OptIn(ExperimentalMaterial3Api::class) @Composable fun ListContent( state: ListUiState, onTypeSelected: (Long?) -> Unit, onAddClick: () -> Unit, onItemClick: (Long) -> Unit ) { Scaffold( topBar = { TopAppBar(title = { Text("My Catalogue") }) }, floatingActionButton = { FloatingActionButton(onClick = onAddClick) { Icon(Icons.Filled.Add, contentDescription = "Add item") } } ) { innerPadding -> Column(Modifier.padding(innerPadding)) { TypeFilterRow(state, onTypeSelected) when { state.isLoading -> Unit state.items.isEmpty() -> EmptyMessage(hasAnyItems = state.totalCount > 0) else -> LazyColumn( contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { items(state.items, key = { it.item.id }) { row -> ItemRow(row, onClick = { onItemClick(row.item.id) }) } } } } } } @Composable private fun TypeFilterRow(state: ListUiState, onTypeSelected: (Long?) -> Unit) { LazyRow( contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { item { FilterChip( selected = state.selectedTypeId == null, onClick = { onTypeSelected(null) }, label = { Text("All") } ) } items(state.types, key = { it.id }) { type -> FilterChip( selected = state.selectedTypeId == type.id, onClick = { onTypeSelected(type.id) }, label = { Text(type.name) } ) } } } @Composable private fun ItemRow(row: ItemWithDetails, onClick: () -> Unit) { Card(modifier = Modifier.fillMaxWidth().clickable(onClick = onClick)) { Column(Modifier.padding(16.dp)) { Text(row.item.title, style = MaterialTheme.typography.titleMedium, maxLines = 2, overflow = TextOverflow.Ellipsis) val byline = listOfNotNull( row.item.creator.ifBlank { null }, row.item.releaseYear?.toString() ).joinToString(" ยท ") if (byline.isNotEmpty()) { Text(byline, style = MaterialTheme.typography.bodyMedium) } Text( text = (listOf(row.type.name) + row.tags.map { it.name }).joinToString(" ยท "), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary ) } } } @Composable private fun EmptyMessage(hasAnyItems: Boolean) { Box(Modifier.fillMaxSize().padding(32.dp), contentAlignment = Alignment.Center) { Text( text = if (hasAnyItems) "Nothing of this type yet." else "Your catalogue is empty. Tap + to add your first item.", style = MaterialTheme.typography.bodyLarge ) } }

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.

@Composable fun CatalogueApp() { ListScreen( onAddClick = { /* Chapter 6 */ }, onItemClick = { /* Chapter 5 */ } ) }

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.

Compare with the iOS course
In Personal Catalogue: iOS (Swift & SwiftUI) Chapter 4, @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

Exercise 1

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.

๐Ÿ“„ View solution
Exercise 2

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.

๐Ÿ“„ View solution
Exercise 3

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.

๐Ÿ“„ View solution

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 the StateFlow
  • @HiltViewModel + @Inject constructor; in a screen: hiltViewModel()
  • val state by vm.uiState.collectAsStateWithLifecycle() (needs lifecycle-runtime-compose)
  • LazyColumn { items(list, key = { it.id }) { ... } }: only visible rows are composed; keys keep row identity
  • FilterChip(selected, onClick, label) in a LazyRow for the type filter; null type id means All
  • Two empty states: no items at all, and no items of the chosen type (decide with totalCount)
Not Yet Verified
Checked (one web search on 2026-11-19): that 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.
Sources for This Chapter
Search results (2026-11-19): collectAsStateWithLifecycle API reference; State holders and UI state; Where to hoist state; Filter a list while typing; Use Kotlin coroutines with lifecycle-aware components. Only titles and short summaries in the search results were used.
Coming next
Personal Catalogue: Android (Kotlin & Compose) 5 adds Navigation Compose: tapping a row opens a detail screen for that item, passing its id, with a delete button and a confirmation dialog.