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
- Why ViewModel Survives Rotation
- viewModel() in a Composable
- Modeling a UiState Data Class
- collectAsStateWithLifecycle