Skip to main content

Mobile development · Intermediate · 26 min

Manage state and lists in Jetpack Compose with a ViewModel

By Padding · Updated 18 Nov 2026
Eclipse Temurin JDK 25 · Kotlin 2.4.21 · Android Gradle Plugin 9.5.3 · Compose BOM 2026.11.01 · Lifecycle 2.11.1

You will build a market list app whose ViewModel exposes loading, error and content states through a StateFlow, draw the items in a LazyColumn with stable keys, keep a draft through rotation with rememberSaveable, and prove the ViewModel with plain unit tests.

On this page

A Compose screen redraws itself from state. When the state changes, the functions that read it run again and the screen shows the new values. That makes the questions that matter "where does each piece of state live?" and "who is allowed to change it?". Get them wrong and you see the usual bugs: a list that reloads every time the phone is rotated, a half-typed entry that vanishes, or a loading spinner that never goes away after an error.

In this tutorial you build a small market list app. It loads a shopping list from a repository (a stand-in for a server that is slow on the first call and sometimes fails), shows a spinner, an error with a retry button, or the list. The reader of your app can add items, tick them off and remove them. You put the list and its loading state in a ViewModel, which survives rotation, and expose it as one StateFlow of a sealed MarketUiState. The composables receive that state and send events back up; they never change the list themselves. That one-way loop is called unidirectional data flow.

You work in ~/market-list-demo, a throwaway folder, and build with the project's own Gradle wrapper, ./gradlew, which you generate from the Gradle 9.9.2 you downloaded to ~/.local/opt/gradle-9.9.2 in the first Compose tutorial. The ViewModel is tested with plain JUnit assertions and kotlinx-coroutines-test, so the important logic is proved on your computer without an emulator.

Step 1 · Install the SDK packages this project compiles against

The Compose BOM 2026.11.01 brings in Compose UI 1.13, which must be compiled against Android API 37.1, and Lifecycle 2.11 needs API 37. Android Gradle Plugin 9.5 uses SDK Build Tools 36.0.0 by default. Check your tools are in place, then install both packages with sdkmanager. Together they are a download of roughly 130 MB, so use Wi-Fi if you are on prepaid mobile data:

Bash
echo "$ANDROID_HOME"
~/.local/opt/gradle-9.9.2/bin/gradle --version
sdkmanager --install "platforms;android-37.1" "build-tools;36.0.0"
sdkmanager --list_installed

If sdkmanager asks you to accept a licence, read it and answer y.

If echo "$ANDROID_HOME" prints an empty line, or sdkmanager is not found, go back to the first Compose tutorial and finish its SDK step. If the Gradle line says No such file or directory, you deleted ~/.local/opt/gradle-9.9.2 after the first tutorial; download it again and check its checksum:

Bash
cd "$(mktemp -d)"
curl -fsSLO https://services.gradle.org/distributions/gradle-9.9.2-bin.zip
echo "971fcd7150ca4ba04852c0b2ca0d2d0ab9468e14b03473eab19528809914c76b  gradle-9.9.2-bin.zip" | sha256sum -c -
mkdir -p ~/.local/opt
unzip -q gradle-9.9.2-bin.zip -d ~/.local/opt
cd -

Check it worked

~/.local/opt/gradle-9.9.2/bin/gradle --version reports Gradle 9.9.2, and the installed list includes lines starting with build-tools;36.0.0 and platforms;android-37.1.

Step 2 · Create the project files

Create the project folder with a settings file, a version catalog and the two build scripts. Android Studio's "Empty Activity" template produces something close to this; writing it yourself means you know what every line is for:

Bash
mkdir -p ~/market-list-demo/gradle
cd ~/market-list-demo

cat > settings.gradle.kts <<'EOF'
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}
rootProject.name = "MarketList"
include(":app")
EOF

cat > gradle/libs.versions.toml <<'EOF'
[versions]
agp = "9.5.3"
kotlin = "2.4.21"
composeBom = "2026.11.01"
activityCompose = "1.13.0"
lifecycle = "2.11.1"
coroutines = "1.11.0"
junit = "4.13.2"

[libraries]
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" }
junit = { group = "junit", name = "junit", version.ref = "junit" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
EOF

cat > build.gradle.kts <<'EOF'
plugins {
    alias(libs.plugins.android.application) apply false
    alias(libs.plugins.kotlin.compose) apply false
}
EOF

cat > gradle.properties <<'EOF'
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
android.useAndroidX=true
EOF

Now the app module. Its build script sets the compile SDK to 37.1 with the release(...) { minorApiLevel = ... } form, and pulls in the ViewModel and lifecycle-aware collection helpers for Compose:

Bash
mkdir -p app/src/main/kotlin/com/example/marketlist app/src/test/kotlin/com/example/marketlist

cat > app/build.gradle.kts <<'EOF'
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.compose)
}

android {
    namespace = "com.example.marketlist"
    compileSdk {
        version = release(37) { minorApiLevel = 1 }
    }
    defaultConfig {
        applicationId = "com.example.marketlist"
        minSdk = 24
        targetSdk = 37
        versionCode = 1
        versionName = "1.0"
    }
    buildFeatures {
        compose = true
    }
}

dependencies {
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.compose.material3)
    implementation(libs.androidx.compose.ui.tooling.preview)
    debugImplementation(libs.androidx.compose.ui.tooling)
    implementation(libs.androidx.activity.compose)
    implementation(libs.androidx.lifecycle.viewmodel.compose)
    implementation(libs.androidx.lifecycle.runtime.compose)

    testImplementation(libs.junit)
    testImplementation(libs.kotlinx.coroutines.test)
}
EOF

cat > app/src/main/AndroidManifest.xml <<'EOF'
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:label="Market list"
        android:theme="@android:style/Theme.Material.Light.NoActionBar">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
EOF

Last, give the project its own Gradle wrapper. You need the downloaded Gradle once to create it; after that, ./gradlew fetches Gradle 9.9.2 for anyone who opens the project, and --gradle-distribution-sha256-sum makes it check that download against the published checksum:

Bash
~/.local/opt/gradle-9.9.2/bin/gradle wrapper --gradle-version 9.9.2 --gradle-distribution-sha256-sum 971fcd7150ca4ba04852c0b2ca0d2d0ab9468e14b03473eab19528809914c76b --no-daemon
./gradlew --version

From here on every command uses ./gradlew, run from ~/market-list-demo.

A few things to notice:

  • There is no org.jetbrains.kotlin.android plugin. Android Gradle Plugin 9 compiles Kotlin itself; you only add the Compose compiler plugin, which shares the Kotlin version number.
  • The BOM is a platform(...) dependency, so the Compose libraries have no version of their own. Upgrading Compose means changing one line in the catalog.
  • minSdk = 24 is the lowest Compose UI 1.13 and Material 3 1.5 accept. Android 7.0 phones are still in use on many second-hand markets, so do not raise it without a reason.

Check it worked

Bash
./gradlew --console=plain :app:tasks --group verification

./gradlew --version reports Gradle 9.9.2. The first run downloads the Android Gradle Plugin and Compose, a few hundred megabytes, so it takes several minutes. It ends with BUILD SUCCESSFUL and the task list includes testDebugUnitTest. An error mentioning compileSdk or android-37.1 means the SDK package from the previous step is missing.

Step 3 · Describe the screen as a sealed UI state

Before you write any composable, decide what the screen can show. This one shows exactly one of three things: a spinner while the list loads, a message with a retry button when loading fails, or the list itself. A sealed interface makes that a closed set, so the compiler tells you if a when forgets one, and it rules out impossible mixes such as "loading and showing an error at once" that separate boolean flags allow.

Create the item, the UI state and the repository:

Bash
cat > app/src/main/kotlin/com/example/marketlist/MarketModel.kt <<'EOF'
package com.example.marketlist

import java.io.IOException
import kotlinx.coroutines.delay

data class MarketItem(
    val id: Long,
    val name: String,
    val quantity: Int,
    val bought: Boolean = false,
)

sealed interface MarketUiState {
    data object Loading : MarketUiState
    data class Error(val message: String) : MarketUiState
    data class Content(val items: List<MarketItem>) : MarketUiState
}

interface ItemsRepository {
    suspend fun loadItems(): List<MarketItem>
}

/** Stands in for a server: slow, and it fails the first call when failFirstLoad is true. */
class FakeItemsRepository(private var failFirstLoad: Boolean = false) : ItemsRepository {
    override suspend fun loadItems(): List<MarketItem> {
        delay(800)
        if (failFirstLoad) {
            failFirstLoad = false
            throw IOException("No connection")
        }
        return listOf(
            MarketItem(id = 1, name = "Rice", quantity = 2),
            MarketItem(id = 2, name = "Tomatoes", quantity = 6),
            MarketItem(id = 3, name = "Ẹ̀wà (beans)", quantity = 1),
            MarketItem(id = 4, name = "Palm oil", quantity = 1),
        )
    }
}
EOF
./gradlew --console=plain -q :app:compileDebugKotlin

Every item has an id that never changes, even when its name or position does. You need that for the list later. The third item is spelt with Yoruba tone marks on purpose: test your lists with the real names your users type, in every language they use, not only plain ASCII.

Check it worked

compileDebugKotlin finishes with no output and no error (the -q flag hides progress). To see the compiler guarding the sealed type, add val x = when (MarketUiState.Loading as MarketUiState) { MarketUiState.Loading -> 1 } inside any function: the build fails because Error and Content are not handled. Remove the line again.

Step 4 · Hold the list in a ViewModel that exposes a StateFlow

The ViewModel owns the list. It keeps the state in a private MutableStateFlow and exposes a read-only StateFlow, so only the ViewModel can change it. The UI calls functions such as addItem and toggleBought: events go up, state comes down.

Bash
cat > app/src/main/kotlin/com/example/marketlist/MarketViewModel.kt <<'EOF'
package com.example.marketlist

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import java.io.IOException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class MarketViewModel(private val repository: ItemsRepository) : ViewModel() {

    private val _uiState = MutableStateFlow<MarketUiState>(MarketUiState.Loading)
    val uiState: StateFlow<MarketUiState> = _uiState.asStateFlow()

    private var nextId = 1000L

    init {
        load()
    }

    fun load() {
        _uiState.value = MarketUiState.Loading
        viewModelScope.launch {
            _uiState.value = try {
                MarketUiState.Content(repository.loadItems())
            } catch (e: IOException) {
                MarketUiState.Error("Could not load your list. Check your connection and try again.")
            }
        }
    }

    fun addItem(name: String) {
        val trimmed = name.trim()
        if (trimmed.isEmpty()) return
        updateItems { items -> items + MarketItem(id = nextId++, name = trimmed, quantity = 1) }
    }

    fun toggleBought(id: Long) {
        updateItems { items -> items.map { if (it.id == id) it.copy(bought = !it.bought) else it } }
    }

    fun remove(id: Long) {
        updateItems { items -> items.filterNot { it.id == id } }
    }

    private fun updateItems(change: (List<MarketItem>) -> List<MarketItem>) {
        _uiState.update { state ->
            if (state is MarketUiState.Content) state.copy(items = change(state.items)) else state
        }
    }
}
EOF
./gradlew --console=plain -q :app:compileDebugKotlin

Why each choice:

  • load() runs from init, once per ViewModel. Because the ViewModel outlives a rotation, the list is not fetched again when the screen is recreated. On a phone with a small prepaid bundle, that is data your user keeps.
  • viewModelScope cancels the load if the screen is closed for good, so nothing writes state after the user has left.
  • The catch names IOException. A bare catch (e: Exception) would also catch the CancellationException that cancels the coroutine and turn a normal cancellation into an error screen.
  • update { } reads and writes the state in one atomic step, and the item functions do nothing unless the list is showing, so a tap during loading cannot create a half list.
  • Every change makes a new list with copy, map or +. Compose and StateFlow notice a new value; they cannot notice a list you changed in place.

Check it worked

The compile finishes with no output. Open MarketViewModel.kt and confirm that nothing outside the class can reach _uiState: it is private, and uiState is typed as StateFlow, which has no setter.

Step 5 · Test the ViewModel with plain assertions

Because the ViewModel holds all the logic and knows nothing about composables, you can test it as ordinary Kotlin. viewModelScope runs on the main dispatcher, which does not exist in a unit test, so the test swaps it for a StandardTestDispatcher with Dispatchers.setMain. runTest shares that dispatcher's virtual clock, so advanceUntilIdle() skips the repository's delay instantly.

Bash
cat > app/src/test/kotlin/com/example/marketlist/MarketViewModelTest.kt <<'EOF'
package com.example.marketlist

import java.io.IOException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test

private class TestRepository(private var failuresLeft: Int = 0) : ItemsRepository {
    override suspend fun loadItems(): List<MarketItem> {
        delay(500)
        if (failuresLeft > 0) {
            failuresLeft--
            throw IOException("offline")
        }
        return listOf(MarketItem(1, "Rice", 2), MarketItem(2, "Tomatoes", 6))
    }
}

@OptIn(ExperimentalCoroutinesApi::class)
class MarketViewModelTest {

    @Before
    fun setUp() {
        Dispatchers.setMain(StandardTestDispatcher())
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
    }

    private fun MarketViewModel.items(): List<MarketItem> {
        val state = uiState.value
        assertTrue("expected Content but was $state", state is MarketUiState.Content)
        return (state as MarketUiState.Content).items
    }

    @Test
    fun startsLoadingThenShowsTheList() = runTest {
        val viewModel = MarketViewModel(TestRepository())
        assertEquals(MarketUiState.Loading, viewModel.uiState.value)

        advanceUntilIdle()

        assertEquals(listOf("Rice", "Tomatoes"), viewModel.items().map { it.name })
    }

    @Test
    fun showsAnErrorAndRecoversOnRetry() = runTest {
        val viewModel = MarketViewModel(TestRepository(failuresLeft = 1))
        advanceUntilIdle()
        assertTrue(viewModel.uiState.value is MarketUiState.Error)

        viewModel.load()
        assertEquals(MarketUiState.Loading, viewModel.uiState.value)
        advanceUntilIdle()

        assertEquals(2, viewModel.items().size)
    }

    @Test
    fun addTrimsTheNameAndIgnoresBlanks() = runTest {
        val viewModel = MarketViewModel(TestRepository())
        advanceUntilIdle()

        viewModel.addItem("  Garri  ")
        viewModel.addItem("   ")

        val names = viewModel.items().map { it.name }
        assertEquals(listOf("Rice", "Tomatoes", "Garri"), names)
    }

    @Test
    fun toggleChangesOnlyTheTappedItem() = runTest {
        val viewModel = MarketViewModel(TestRepository())
        advanceUntilIdle()

        viewModel.toggleBought(2)

        assertEquals(listOf(false, true), viewModel.items().map { it.bought })
    }

    @Test
    fun removeKeepsTheOtherItemsAndTheirIds() = runTest {
        val viewModel = MarketViewModel(TestRepository())
        advanceUntilIdle()

        viewModel.remove(1)

        assertEquals(listOf(2L), viewModel.items().map { it.id })
    }
}
EOF
./gradlew --console=plain :app:testDebugUnitTest

These are local unit tests: they run on your computer's JVM, not on a device, in a few seconds. That is where most of your state logic should be tested. Compose UI tests, which tap real buttons on a rendered screen, are instrumented tests that need an emulator or phone, and they are a topic of their own.

Check it worked

The build ends with BUILD SUCCESSFUL. Open app/build/reports/tests/testDebugUnitTest/index.html in a browser: it shows 5 tests, 0 failures. To see a test catch a bug, change items + MarketItem(...) in addItem to listOf(MarketItem(...)), run the tests again and watch addTrimsTheNameAndIgnoresBlanks fail, then put the line back.

Step 6 · Draw the list with LazyColumn and stable keys

Now the screen. MarketScreen is stateless: it receives a MarketUiState and one lambda per event, and it never holds the list. That is state hoisting. You can preview a stateless screen with made-up data and reuse it anywhere.

Bash
cat > app/src/main/kotlin/com/example/marketlist/MarketScreen.kt <<'EOF'
package com.example.marketlist

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
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.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

@Composable
fun MarketScreen(
    state: MarketUiState,
    onRetry: () -> Unit,
    onAdd: (String) -> Unit,
    onToggle: (Long) -> Unit,
    onRemove: (Long) -> Unit,
    modifier: Modifier = Modifier,
) {
    Scaffold(modifier = modifier) { innerPadding ->
        val content = Modifier.fillMaxSize().padding(innerPadding)
        when (state) {
            MarketUiState.Loading -> Box(content, contentAlignment = Alignment.Center) {
                CircularProgressIndicator()
            }
            is MarketUiState.Error -> Column(
                modifier = content.padding(24.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Text(state.message)
                Button(onClick = onRetry, modifier = Modifier.padding(top = 16.dp)) {
                    Text("Try again")
                }
            }
            is MarketUiState.Content -> Column(content) {
                AddItemRow(onAdd = onAdd)
                LazyColumn(modifier = Modifier.fillMaxSize()) {
                    items(state.items, key = { it.id }) { item ->
                        ItemRow(
                            item = item,
                            onToggle = { onToggle(item.id) },
                            onRemove = { onRemove(item.id) },
                            modifier = Modifier.animateItem(),
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun ItemRow(item: MarketItem, onToggle: () -> Unit, onRemove: () -> Unit, modifier: Modifier = Modifier) {
    ListItem(
        modifier = modifier,
        leadingContent = { Checkbox(checked = item.bought, onCheckedChange = { onToggle() }) },
        headlineContent = {
            Text(
                text = item.name,
                textDecoration = if (item.bought) TextDecoration.LineThrough else null,
            )
        },
        supportingContent = { Text("Quantity: ${item.quantity}") },
        trailingContent = { TextButton(onClick = onRemove) { Text("Remove") } },
    )
}

@Composable
fun AddItemRow(onAdd: (String) -> Unit, modifier: Modifier = Modifier) {
    var draft by rememberSaveable { mutableStateOf("") }
    Row(
        modifier = modifier.fillMaxWidth().padding(16.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        OutlinedTextField(
            value = draft,
            onValueChange = { draft = it },
            label = { Text("New item") },
            singleLine = true,
            modifier = Modifier.weight(1f),
        )
        Button(
            onClick = {
                onAdd(draft)
                draft = ""
            },
            enabled = draft.isNotBlank(),
            modifier = Modifier.padding(start = 8.dp),
        ) {
            Text("Add")
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun MarketScreenPreview() {
    MaterialTheme {
        MarketScreen(
            state = MarketUiState.Content(
                listOf(MarketItem(1, "Rice", 2), MarketItem(3, "Ẹ̀wà (beans)", 1, bought = true)),
            ),
            onRetry = {},
            onAdd = {},
            onToggle = {},
            onRemove = {},
        )
    }
}
EOF
./gradlew --console=plain -q :app:compileDebugKotlin

LazyColumn only composes the rows that are on screen, which keeps a long list smooth on a low-end phone. The key = { it.id } argument matters as soon as items move. Without a key, Compose tracks rows by position: remove the first item and every row below is treated as a different item that changed, and any state a row holds slides onto its neighbour. With the stable id as the key, Compose knows which row went away, keeps the rest as they are, and Modifier.animateItem() can slide them into place. Never use the list index or the name as a key; two items can share a name.

ItemRow takes onToggle: () -> Unit rather than the ViewModel. It does not know where the data lives, so the preview can pass empty lambdas.

Check it worked

The compile finishes with no output. If you use Android Studio, open MarketScreen.kt and the split view shows MarketScreenPreview: two rows, the second one ticked and struck through, with its tone marks drawn correctly.

Step 7 · Choose between remember and rememberSaveable

Not every piece of state belongs in the ViewModel. The half-typed text in the "New item" field matters only to that field until the user taps Add, so AddItemRow keeps it itself. The question is how long it must last.

  • remember keeps a value while the composable stays in the composition. Rotating the phone, changing the system language or switching to dark mode recreates the activity by default, and a remembered value is lost.
  • rememberSaveable also writes the value into the saved instance state, so it comes back after the activity is recreated and even after Android kills the app in the background to free memory and the user returns to it. It only accepts values that fit in a Bundle (strings, numbers and parcelable types) or ones you give a Saver, and it is meant for small values.
  • The ViewModel survives recreation too, but not the process being killed. That is why the list is reloaded from the repository then, and why a repository backed by a local database is the next thing a real app adds.

The rule of thumb: data the app cares about lives in the ViewModel (and below it, storage); short-lived input that belongs to one element uses rememberSaveable; values that are cheap to recompute, such as an animation's progress, use remember.

AddItemRow in the previous step already uses rememberSaveable. To see the difference for yourself on a device, you would temporarily change that line, and add the matching import next to the other androidx.compose.runtime imports at the top of MarketScreen.kt:

Kotlin
import androidx.compose.runtime.remember

var draft by remember { mutableStateOf("") }

Check it worked

Confirm the field uses the saveable version:

Bash
grep -n 'rememberSaveable { mutableStateOf("") }' app/src/main/kotlin/com/example/marketlist/MarketScreen.kt

It prints one line from AddItemRow. When you run the app in the last step, type "Garri" without tapping Add and rotate the phone: the text is still there. With remember instead, the field comes back empty.

Step 8 · Collect the state in the activity and build the app

The last piece connects the ViewModel to the screen. MarketRoute gets the ViewModel with viewModel { ... }, which creates it the first time and hands back the same instance after rotation. collectAsStateWithLifecycle() turns the StateFlow into Compose state, and it only collects while the screen is at least started. When the app goes to the background it stops collecting, so the screen does no work while nobody can see it. The ViewModel and its StateFlow carry on; only the screen's collection pauses.

Bash
cat > app/src/main/kotlin/com/example/marketlist/MainActivity.kt <<'EOF'
package com.example.marketlist

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MaterialTheme {
                MarketRoute()
            }
        }
    }
}

@Composable
fun MarketRoute(
    viewModel: MarketViewModel = viewModel { MarketViewModel(FakeItemsRepository(failFirstLoad = true)) },
) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    MarketScreen(
        state = state,
        onRetry = viewModel::load,
        onAdd = viewModel::addItem,
        onToggle = viewModel::toggleBought,
        onRemove = viewModel::remove,
    )
}
EOF
./gradlew --console=plain :app:assembleDebug
ls -l app/build/outputs/apk/debug/

MarketRoute is the only composable that knows about the ViewModel. Everything below it receives plain values and lambdas, which is the unidirectional loop from the introduction: state flows down from uiState, events flow up through viewModel::addItem and the others. The repository is told to fail its first load so you can see the error state once.

To run it, open ~/market-list-demo in Android Studio and press Run with an emulator or phone selected, or install the APK with adb from the SDK's platform tools:

Bash
adb install -r app/build/outputs/apk/debug/app-debug.apk

Check it worked

assembleDebug ends with BUILD SUCCESSFUL and the listing shows app-debug.apk. On a device, the app opens on a spinner, then shows "Could not load your list". Tap Try again: the spinner returns and four items appear. Tick Tomatoes, add an item, remove Rice and watch the rows slide. Then rotate the phone: the list stays exactly as you left it and no spinner appears, because the ViewModel kept it.

Next steps

You now have the shape most Compose screens use: a ViewModel holding a sealed UI state in a StateFlow, a stateless screen that renders it, and tests that prove the logic without a device.

When you have finished experimenting, delete the demo project with rm -rf ~/market-list-demo. The SDK packages stay in $ANDROID_HOME for your next project.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.