collectAsStateWithLifecycle
Observe de forma segura el estado de ViewModel en Compose.
collectAsStateWithLifecycle es una lección gratuita de Jetpack Compose Academy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Jetpack Compose Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Jetpack Compose Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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()Why Not collectAsState
Plain collectAsState() keeps collecting even when the app is in the background, wasting work. The lifecycle version pauses instead.
Stops in the Background
When your screen stops, collection stops too; when it returns to the foreground, collection resumes, saving battery and avoiding pointless updates.
Reading the Result
The call returns a State you read with by, giving you a normal value that triggers recomposition whenever the flow emits.
val ui by vm.state.collectAsStateWithLifecycle()
Text(ui.title)Add the Dependency
This helper lives in a runtime artifact. Add lifecycle-runtime-compose so the function is available in your Composables.
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.0")Choosing the Min State
By default collection is active while at least STARTED. You can lower the threshold, but STARTED is the safe, recommended choice.
Pairs With StateFlow
It shines with StateFlow, which always holds a current value, so your screen has something to show the instant it appears.
Branch on the State
Once collected, branch on the UiState to render loading, success, or error, all driven by the latest emission from your ViewModel.
if (ui.isLoading) Spinner() else Content(ui.items)Safer Than Manual Collection
It frees you from manually starting and cancelling collection. The helper ties the work to composition and lifecycle for you. ✨
The Modern Default
For new Compose screens, collectAsStateWithLifecycle() is the recommended way to observe ViewModel state safely and efficiently.
Quick Check
Check why the lifecycle-aware collector is preferred.
Recap
Observe ViewModel state with collectAsStateWithLifecycle(): it collects a StateFlow into Compose state, pauses in the background, and is the modern default.
Preguntas frecuentes
¿La lección «collectAsStateWithLifecycle» es gratis?
Sí — el texto completo de «collectAsStateWithLifecycle» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Jetpack Compose Academy, actualiza a CoddyKit PRO. El curso de Jetpack Compose Academy incluye 4 lecciones en total.
¿Qué aprenderé en «collectAsStateWithLifecycle»?
Observe de forma segura el estado de ViewModel en Compose. Practicas Jetpack Compose Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Jetpack Compose Academy?
No se requiere experiencia previa. Jetpack Compose Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «collectAsStateWithLifecycle»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Jetpack Compose Academy?
Sí. Cada lección de Jetpack Compose Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Por qué ViewModel sobrevive a la rotación
- viewModel() en un Composable
- Modelar una clase de datos UiState
- collectAsStateWithLifecycle