0Pricing
Jetpack Compose Academy · Lezione

collectAsStateWithLifecycle

Osservi in sicurezza lo stato del ViewModel in Compose.

collectAsStateWithLifecycle è una lezione Jetpack Compose Academy gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Jetpack Compose Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Jetpack Compose Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «collectAsStateWithLifecycle» è gratuita?

Sì — il testo completo di «collectAsStateWithLifecycle» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Jetpack Compose Academy, passa a CoddyKit PRO. Il corso Jetpack Compose Academy include 4 lezioni in totale.

Cosa imparerò in «collectAsStateWithLifecycle»?

Osservi in sicurezza lo stato del ViewModel in Compose. Eserciti Jetpack Compose Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Jetpack Compose Academy?

Non è richiesta alcuna esperienza precedente. Jetpack Compose Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «collectAsStateWithLifecycle»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Jetpack Compose Academy?

Sì. Ogni lezione Jetpack Compose Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Perché il ViewModel sopravvive alla rotazione
  2. viewModel() in una Composable
  3. Modellare una classe dati UiState
  4. collectAsStateWithLifecycle
← Torna a Jetpack Compose Academy