0Pricing
Jetpack Compose Academy · Lesson

collectAsStateWithLifecycle

Observe ViewModel state safely in Compose.

Observing a Flow in Compose

Your ViewModel exposes state as a Flow, and your Composable needs to turn that stream into a value Compose can read and react to.

The Lifecycle-Aware Way

Use collectAsStateWithLifecycle() to collect a StateFlow into Compose state while respecting the screen’s lifecycle. 🔋

val ui by vm.state.collectAsStateWithLifecycle()

All lessons in this course

  1. Why ViewModel Survives Rotation
  2. viewModel() in a Composable
  3. Modeling a UiState Data Class
  4. collectAsStateWithLifecycle
← Back to Jetpack Compose Academy