Skip to content
Commitwise
Menu

What's the difference between StateFlow, SharedFlow and Channel, and when do you use each?

AndroidMid-level

In shortStateFlow holds a current value and conflates updates, ideal for UI state. SharedFlow broadcasts events to all current collectors, with configurable replay and buffering. A Channel delivers each element to exactly one receiver, useful for one-off work queues. For one-time UI events, prefer modeling them as state or use a channel carefully.

Model answer

Cold vs hot: a regular Flow is cold (it runs per collector). StateFlow and SharedFlow are hot: they exist independently of collectors.

StateFlow: always has a current value, new collectors get it immediately, updates are conflated (slow collectors see only the latest), and equal values aren’t re-emitted. Perfect for UI state: a ViewModel exposes StateFlow<UiState>, the UI collects it with collectAsStateWithLifecycle(). Create it from other flows with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial).

SharedFlow: broadcasts each emission to all current collectors; replay decides how many past values new collectors get, extraBufferCapacity and onBufferOverflow control backpressure. Good for app-wide event streams (a logout signal several components react to).

Channel: each element is received by exactly one collector, buffered or rendezvous; it’s a queue between coroutines. Good for work queues and fan-out to workers.

One-off UI events (show a snackbar, navigate): a StateFlow would replay them after rotation, and a SharedFlow without replay can drop them when nobody is collecting. Prefer modeling them as state that the UI consumes and clears (message: String? plus onMessageShown()), or use a Channel received as a flow with lifecycle-aware collection, accepting its edge cases.

What they're looking for

Hot vs cold flows, StateFlow semantics (current value, conflation, equality), SharedFlow parameters, Channel delivery semantics, lifecycle-aware collection, and the one-off event debate.

Common mistakes

  • Using StateFlow for events that must not be lost or repeated.
  • Collecting flows in the UI without lifecycle awareness.
  • Using a SharedFlow with replay for navigation events, replaying them after rotation.

More android questions

Esc

Type to search the whole site.