0Pricing
Jetpack Compose Academy · Aula

collectAsStateWithLifecycle

Observe o estado do ViewModel com segurança no Compose.

collectAsStateWithLifecycle é uma aula grátis de Jetpack Compose Academy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Jetpack Compose Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Jetpack Compose Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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.

Perguntas Frequentes

A aula “collectAsStateWithLifecycle” é grátis?

Sim — o texto completo de “collectAsStateWithLifecycle” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Jetpack Compose Academy, atualize para CoddyKit PRO. O curso de Jetpack Compose Academy inclui 4 aulas no total.

O que vou aprender em “collectAsStateWithLifecycle”?

Observe o estado do ViewModel com segurança no Compose. Você pratica Jetpack Compose Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Jetpack Compose Academy?

Nenhuma experiência prévia é necessária. Jetpack Compose Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “collectAsStateWithLifecycle”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Jetpack Compose Academy?

Sim. Cada aula de Jetpack Compose Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Por que o ViewModel Sobrevive à Rotação
  2. viewModel() em uma Composable
  3. Modelando uma Classe de Dados UiState
  4. collectAsStateWithLifecycle
← Voltar para Jetpack Compose Academy