collectAsStateWithLifecycle

Jetpack Compose Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Fill the blank

Read the ViewModel's state in a lifecycle-aware way.

@Composable
fun NotesRoute(vm: NotesListViewModel) {
    val notes by vm.notes.____()
    Column { notes.forEach { Text(it) } }
}
Options
Hint 1 of 1

Which one knows about the lifecycle?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A collectAsStateWithLifecycle

Correct. It stops collecting below STARTED.

Why not the others?
  • B collectAsState. It compiles, but keeps collecting while the app is in the background.
  • C observeAsState. That's for LiveData.
  • D collect. collect suspends and returns nothing; you can't call it in a composable body.

30-second answer

Use val state by viewModel.state.collectAsStateWithLifecycle(). It collects only while the lifecycle is at least STARTED, so nothing runs in the background, and it turns each value into Compose State. collectAsState keeps collecting while the composable is in composition, even when the app is backgrounded.

Practise saying it · 25 s. No recording, just a timer

Explain how to read a StateFlow in Compose.

Say your answer out loud, then check which of these points you covered:

  • collectAsStateWithLifecycle
  • Stops below STARTED
  • Collect at screen level
  • Pairs with WhileSubscribed

Deep dive

It's in androidx.lifecycle:lifecycle-runtime-compose.

Collect at the screen level and pass plain values down; don't pass Flows into child composables.

Combined with stateIn(WhileSubscribed(5_000)), the upstream stops 5 seconds after the app goes to the background.

collectAsState remains right where there is no lifecycle owner; recent Lifecycle versions also make collectAsStateWithLifecycle available in Compose Multiplatform.

The ViewModel used above Compile-checked · Kotlin 2.4.21
class NotesListViewModel : ViewModel() {
    val notes: StateFlow<List<String>> = MutableStateFlow(listOf("First"))
}

Common mistakes

  • Using collectAsState on Android and collecting in the background.
  • Collecting the same flow in many child composables.
  • Passing the Flow itself as a parameter.

Senior take & follow-ups

Name the API and the lifecycle state, then the pairing with WhileSubscribed.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why does this matter for battery?

    Show hint

    Background collection keeps upstream work like GPS or database queries alive.

  2. What's the minimum state by default?

    Show hint

    Lifecycle.State.STARTED.

Suggest a fix if something here is wrong or out of date.