0Pricing
Jetpack Compose Academy · Aula

StateFlow versus SharedFlow

Escolha o fluxo ativo correto para a interface.

StateFlow versus SharedFlow é uma aula grátis de Jetpack Compose Academy no CoddyKit. Esta é a aula 1 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.

Hot Streams for the UI

To stream live data into Compose you use a hot flow that stays active and emits whether or not anyone is currently collecting it.

Meet StateFlow

A StateFlow always holds exactly one current value. New collectors immediately receive that latest value, which is perfect for screen state. 📦

val count = MutableStateFlow(0)
count.value = 1

Read the Value Anytime

Because StateFlow caches one item, you can read its current value synchronously through the value property without collecting.

val ui: StateFlow<UiState> = _ui
val now = ui.value

StateFlow Skips Duplicates

A StateFlow only emits when the value actually changes. Setting it to the same value again sends nothing to collectors.

_count.value = 5
_count.value = 5 // no new emission

Meet SharedFlow

A SharedFlow broadcasts events to many collectors but holds no required current value. It is built for things that happen, not state that is.

val events = MutableSharedFlow<String>()

SharedFlow Replay Buffer

A SharedFlow can replay a few past emissions to late collectors. With replay zero, new collectors only see future events.

MutableSharedFlow<Int>(replay = 1)

SharedFlow Keeps Duplicates

Unlike StateFlow, a SharedFlow emits every value you send, even repeats. Two identical taps fire two separate events.

events.emit("tap")
events.emit("tap") // both delivered

State Versus Events

The rule of thumb: use StateFlow for what the screen looks like, and SharedFlow for one-time things like a navigation or a toast.

Expose Read-Only Streams

Keep a private mutable flow inside the ViewModel and expose a read-only one. The UI observes but cannot mutate it.

private val _ui = MutableStateFlow(UiState())
val ui: StateFlow<UiState> = _ui

StateFlow Needs a Default

A StateFlow must start with an initial value, so the UI always has something to show. A SharedFlow can start empty.

MutableStateFlow(UiState(loading = true))

Collect in Compose

You turn either flow into Compose state with a collector. For a StateFlow the screen has data immediately on first frame.

val state by viewModel.ui.collectAsStateWithLifecycle()

Quick Check

Match each flow to its purpose.

Recap: StateFlow vs SharedFlow

Nice! StateFlow caches one current value for screen state, while SharedFlow broadcasts repeatable events with an optional replay buffer. 🎯

Perguntas Frequentes

A aula “StateFlow versus SharedFlow” é grátis?

Sim — o texto completo de “StateFlow versus SharedFlow” é 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 “StateFlow versus SharedFlow”?

Escolha o fluxo ativo correto para a interface. 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 1 de 4.

Quanto tempo leva a aula “StateFlow versus SharedFlow”?

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