0Pricing
Jetpack Compose Academy · Aula

stateIn e WhileSubscribed

Armazene fluxos em cache e interrompa o trabalho quando ninguém estiver ouvindo.

stateIn e WhileSubscribed é uma aula grátis de Jetpack Compose Academy no CoddyKit. Esta é a aula 3 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.

From Cold Flow to Hot State

UI state should be hot and cached, but your transformed flows are cold. The stateIn operator converts a cold flow into a StateFlow.

What stateIn Does

stateIn launches the upstream flow in a scope, shares one collection across all collectors, and caches the latest value for new ones.

val ui = source.stateIn(
    viewModelScope, started, initial)

It Needs a Scope

The first argument is a scope, usually viewModelScope, which ties the running flow to the ViewModel lifecycle.

flow.stateIn(viewModelScope, ...)

It Needs an Initial Value

Because a StateFlow always holds a value, stateIn requires an initial one to show before the first real emission arrives.

flow.stateIn(scope, started,
    initialValue = UiState.Loading)

The Sharing Strategy

The middle argument is the SharingStarted policy. It decides exactly when the upstream flow starts and stops running.

Eagerly and Lazily

SharingStarted.Eagerly starts the flow immediately and never stops it, while Lazily starts on the first collector and keeps going.

started = SharingStarted.Eagerly

Meet WhileSubscribed

WhileSubscribed only runs the upstream flow while there is at least one active collector, then stops it when the last one leaves.

started = SharingStarted.WhileSubscribed()

The Five Second Timeout

Passing a small timeout to WhileSubscribed keeps the flow alive briefly after the last collector, surviving quick rotations.

SharingStarted.WhileSubscribed(5000)

Why the Timeout Helps

During a screen rotation the old collector leaves and a new one arrives moments later. The timeout avoids a needless restart in between.

Stops Wasted Work

With WhileSubscribed a database or network flow pauses when the screen is off, then resumes when the user returns. Battery wins. 🔋

A Full stateIn Recipe

Put it together: transform your data, then call stateIn with the scope, WhileSubscribed, and an initial loading state.

val ui = repo.flow().map { UiState(it) }
    .stateIn(viewModelScope,
        SharingStarted.WhileSubscribed(5000),
        UiState.Loading)

Quick Check

Reason about subscriber-driven lifecycles.

Recap: stateIn & WhileSubscribed

Well done! stateIn turns a cold flow into a cached StateFlow, and WhileSubscribed runs it only while observed so you stop wasting work. 🎯

Perguntas Frequentes

A aula “stateIn e WhileSubscribed” é grátis?

Sim — o texto completo de “stateIn e WhileSubscribed” é 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 “stateIn e WhileSubscribed”?

Armazene fluxos em cache e interrompa o trabalho quando ninguém estiver ouvindo. 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 3 de 4.

Quanto tempo leva a aula “stateIn e WhileSubscribed”?

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. StateFlow versus SharedFlow
  2. Mapeando e Combinando Flows
  3. stateIn e WhileSubscribed
  4. Eventos Únicos com Canais
← Voltar para Jetpack Compose Academy