Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 104 ยท Practice and Review

Practice: Compose and State Exercises

Ten Jetpack Compose exercises with solutions on state hoisting, lists, keys, derived state and side effects, each with a runnable Kotlin stand-in you can change.

You have now met the core ideas of Compose: composables describe the screen, state drives it, and events flow back up to whoever owns the state. Reading about them gives you the vocabulary. Solving small problems gives you the reflexes, and that is what this lesson is for. It has ten exercises on state hoisting, shared state, lists and keys, derived state, and side effects.

Real Compose code needs the Android SDK, so it cannot run on this site. Each exercise therefore has two parts. The real solution is a read-only Compose snippet showing what you would write in an app. The stand-in is a plain Kotlin program you can run and edit here that models the same rule with ordinary functions and classes. Each one says honestly which part is which. Try every task on paper or in Android Studio first, then compare.

flowchart LR
    A["Read the task"] --> B["Write your own answer"]
    B --> C["Open the real solution"]
    C --> D["Run the stand-in and change one thing"]
    D --> E{"Did the result surprise you?"}
    E -- yes --> F["Reread the lesson that teaches it"]
    E -- no --> G["Move to the next exercise"]

The practice loop: attempt first, compare second, then poke at the stand-in.

If an exercise feels shaky, the topic lessons are State and remember, State Hoisting, Recomposition and Stability, rememberSaveable and derivedStateOf, Side Effects and Lazy Lists and Grids.

Part 1: Hoisting and shared state

Exercise 1: make a switch row stateless

Task. A settings row shows a label and a switch. Right now it owns its own checked value with remember. Rewrite it so it is stateless, and write the screen that owns the state.

Hint. The row needs two extra parameters: the current value and a callback that reports the new one.

Kotlin
// read-only example: needs Compose
@Composable
fun SettingRow(
    label: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(modifier, verticalAlignment = Alignment.CenterVertically) {
        Text(label, Modifier.weight(1f))
        Switch(checked = checked, onCheckedChange = onCheckedChange)
    }
}

@Composable
fun SettingsScreen() {
    var notifications by rememberSaveable { mutableStateOf(true) }
    SettingRow("Notifications", notifications, onCheckedChange = { notifications = it })
}

The stand-in below treats the row as a pure function from (label, checked) to a line of text. Because it owns nothing, you can ask for both states without clicking anything.

Kotlin Solution 1: a stateless row (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first two lines are exactly what a Compose preview would show: no state, only inputs.

Exercise 2: one source of truth for two widgets

Task. A temperature screen has a text field for degrees Celsius and a text that shows the Fahrenheit value. Where does the state live, and how many copies of it exist?

Hint. Only the text the user typed is real state. The Fahrenheit number is computed from it.

Kotlin
// read-only example: needs Compose
@Composable
fun TemperatureScreen() {
    var celsius by rememberSaveable { mutableStateOf("20") }
    val fahrenheit = celsius.toDoubleOrNull()?.let { it * 9 / 5 + 32 }

    Column {
        OutlinedTextField(value = celsius, onValueChange = { celsius = it }, label = { Text("Celsius") })
        Text(if (fahrenheit == null) "Not a number" else "Fahrenheit: $fahrenheit")
    }
}

There is one piece of state (celsius) and one derived value. Storing the Fahrenheit number in a second remember would create two copies that can disagree.

Kotlin Solution 2: one value, one derived view (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

-40 is the one temperature that is the same in both scales, a handy sanity check for your own solution.

Exercise 3: filter input in the owner

Task. A PIN field must accept digits only and at most four of them. Where do you enforce that, and what does the field do when the owner refuses a change?

Hint. A text field only reports what the user typed. The owner decides whether to accept it.

Kotlin
// read-only example: needs Compose
@Composable
fun PinField() {
    var pin by rememberSaveable { mutableStateOf("") }
    OutlinedTextField(
        value = pin,
        onValueChange = { new -> if (new.length <= 4 && new.all(Char::isDigit)) pin = new },
        label = { Text("PIN") },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword)
    )
}

If the owner ignores the callback, the text on screen simply does not change. That is the unidirectional loop working as designed.

Kotlin Solution 3: the owner accepts or rejects (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Exercise 4: a state holder for a sign-up form

Task. A sign-up form has an email, a password and a "terms accepted" box. The Submit button is enabled only when the email contains @, the password has at least 8 characters, and the terms box is ticked. Put the state and the rule in one class, and make sure the button state cannot get out of date.

Hint. Do not store canSubmit as a separate variable. Compute it from the three fields.

Kotlin
// read-only example: needs Compose
class SignUpState {
    var email by mutableStateOf("")
    var password by mutableStateOf("")
    var termsAccepted by mutableStateOf(false)

    val canSubmit: Boolean
        get() = "@" in email && password.length >= 8 && termsAccepted
}

@Composable
fun SignUpForm(state: SignUpState = remember { SignUpState() }) {
    Column {
        TextField(state.email, { state.email = it })
        TextField(state.password, { state.password = it })
        Checkbox(state.termsAccepted, { state.termsAccepted = it })
        Button(onClick = { /* submit */ }, enabled = state.canSubmit) { Text("Create account") }
    }
}

Because canSubmit is a getter, it reads the three state values every time. In real Compose those reads are tracked, so the button recomposes when any of them changes.

Kotlin Solution 4: derived canSubmit (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Part 2: Lists and derived state

Exercise 5: keys keep state with the right item

Task. A list of tasks lets you delete the first one. Each row remembers whether it is expanded. After deleting the first task, the row that had been second must still be expanded. What goes wrong without keys, and how do you fix it?

Hint. remember inside an item is attached to a position in the list unless you give the item a key.

Kotlin
// read-only example: needs Compose
LazyColumn {
    items(tasks, key = { it.id }) { task ->
        var expanded by rememberSaveable { mutableStateOf(false) }
        TaskRow(task, expanded, onToggle = { expanded = !expanded })
    }
}

With key = { it.id }, Compose follows each row by its id when the list changes. Without it, rows are matched by position, so the "expanded" state stays at index 1 while a different task moves into that slot.

The stand-in stores the remembered flags in two maps: one keyed by position and one keyed by id.

Kotlin Solution 5: position vs key (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After the delete, the position-matched column marks the wrong task as expanded, and the key-matched column keeps "Write report" expanded.

Exercise 6: which items are composed?

Task. A lazy list has 1,000 rows of 50 dp each in a viewport that is 300 dp tall. The list is scrolled by 275 dp. Which row indexes are visible, and how many composables exist if the list also prepares one extra row on each side?

Hint. The first visible row is offset / itemHeight rounded down; the last visible row is (offset + viewport - 1) / itemHeight.

Kotlin
// read-only example: needs Compose
val listState = rememberLazyListState()
val firstVisible = listState.firstVisibleItemIndex          // 5 after scrolling 275 dp
val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index

Real lazy lists compose only the rows that intersect the viewport plus a small buffer. The stand-in computes that window with integer arithmetic.

Kotlin Solution 6: the visible window (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Only a handful of rows exist at any moment, which is why a list of a million items can still scroll smoothly.

Exercise 7: derived state for a "back to top" button

Task. Show a "back to top" button only when the first visible index is greater than zero. The scroll position changes on every frame, but the button only needs to change twice. How do you avoid recomposing on every scroll step?

Hint. Wrap the condition in derivedStateOf, so readers only see changes of the boolean.

Kotlin
// read-only example: needs Compose
val listState = rememberLazyListState()
val showButton by remember {
    derivedStateOf { listState.firstVisibleItemIndex > 0 }
}

Box {
    LazyColumn(state = listState) { /* items */ }
    if (showButton) {
        FloatingActionButton(onClick = { scope.launch { listState.animateScrollToItem(0) } }) { /* icon */ }
    }
}

The stand-in compares two designs over the same ten scroll positions: one that "recomposes" on every index change and one that only notifies when the derived boolean changes.

Kotlin Solution 7: notify on change of the result (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Part 3: Effects and updates

Exercise 8: restart an effect when its key changes

Task. A screen loads a profile for a userId. When userId changes, the old load must be cancelled and a new one started. Which API gives you that, and what is the key?

Hint. The effect restarts whenever any key passed to it changes.

Kotlin
// read-only example: needs Compose
@Composable
fun ProfileScreen(userId: String, viewModel: ProfileViewModel) {
    LaunchedEffect(userId) {
        viewModel.load(userId)
    }
    /* UI */
}

LaunchedEffect(userId) launches a coroutine when the composable enters the composition, cancels it when userId changes or when the composable leaves, and then starts a new one. Using LaunchedEffect(Unit) would load only once, which is the classic bug here.

The stand-in is a tiny effect runner with one active "job" that is cancelled whenever the key differs from the last one.

Kotlin Solution 8: cancel and restart on key change (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Exercise 9: balance every registration with a cleanup

Task. A composable listens to a sensor while it is on screen. Write it so the listener is removed when the composable leaves the composition, and also when the sensor object it depends on changes.

Hint. DisposableEffect needs an onDispose block as its last statement.

Kotlin
// read-only example: needs Compose
@Composable
fun SensorReading(sensor: Sensor, onValue: (Float) -> Unit) {
    val currentOnValue by rememberUpdatedState(onValue)

    DisposableEffect(sensor) {
        val listener = SensorListener { value -> currentOnValue(value) }
        sensor.register(listener)
        onDispose { sensor.unregister(listener) }
    }
}

Two details matter. The key is sensor, because a new sensor needs a new registration. And the callback is read through rememberUpdatedState, so a new lambda does not force a restart of the whole effect.

The stand-in counts registrations and removals; after any sequence they must differ by exactly the number of listeners still on screen.

Kotlin Solution 9: registered minus removed (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Exercise 10: why mutating a list in place does not update the screen

Task. A screen holds var items by mutableStateOf(mutableListOf("a", "b")) and a button calls items.add("c"). The UI does not change. Explain why, and give two correct fixes.

Hint. Compose observes the assignment of the state's value, not what happens inside the object it points to.

Kotlin
// read-only example: needs Compose
// Fix 1: an observable list
val items = remember { mutableStateListOf("a", "b") }
Button(onClick = { items.add("c") }) { Text("Add") }

// Fix 2: an immutable value that you replace
var items by remember { mutableStateOf(listOf("a", "b")) }
Button(onClick = { items = items + "c" }) { Text("Add") }

The second fix creates a new list and assigns it, which the state object notices because the new value is not equal to the old one. The first fix uses a collection that reports its own changes.

The stand-in models a state cell that notifies observers only when the new value differs from the old one.

Kotlin Solution 10: assign a new value, do not mutate (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The in-place version holds the right data and the UI never hears about it, which is exactly the bug in the task.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A composable receives value and onValueChange but the owner never updates its state in the callback. What does the text field show?

    A hoisted text field does not edit anything by itself. It reports the typed text, and the owner decides whether to accept it. If the state is not updated, the screen keeps the old value.
  2. 2. Why should list items use key = { it.id } when each row remembers something?

    Without keys, rows are matched by position, so remembered state can end up on a different item after an insert or delete.
  3. 3. When is derivedStateOf the right tool?

    derivedStateOf makes readers depend on the result, so a button that depends on index > 0 recomposes only when that boolean flips, not on every scroll step.
  4. 4. Which change makes items.add("c") visible to the UI?

    Compose notices state writes. A plain mutable list mutated in place makes no write to the state, but a mutableStateListOf reports its own changes and a replaced immutable list is a new value.
  5. 5. What must the last statement of a DisposableEffect block be?

    DisposableEffect requires onDispose, which runs when the effect leaves the composition or its key changes, and is where you undo the registration.

Summary

  • Hoist state with a value plus a callback; the owner decides what a change means, so it can filter input.
  • Keep one source of truth and compute everything else from it, as in canSubmit and the Fahrenheit text.
  • Use stable keys for list items so remembered state follows the right item.
  • Lazy lists compose only the visible window plus a small buffer.
  • derivedStateOf limits recomposition to changes of the derived result.
  • LaunchedEffect restarts on key change; DisposableEffect must always undo what it registered.
  • Replace immutable values or use mutableStateListOf; never rely on mutating a plain collection in place.
  • The Compose snippets here are read-only; the runnable TryIt blocks are Kotlin stand-ins for the rules.

Next: Practice: Architecture, Navigation and Data Exercises