StateFlow & SharedFlow
KOTLIN › Flow
Hot flows for UI state versus one-off events, and why a Channel is often the better event bus.
Interviewers use StateFlow and SharedFlow to test whether you can model UI state separately from one-time events. Expect to defend why StateFlow needs an initial value and conflates, why that conflation makes it actively wrong for events, and what replay and extraBufferCapacity buy you. A strong answer goes further and admits SharedFlow is an imperfect event bus at either replay setting, reaching for a Channel with receiveAsFlow when a single screen consumes one-off events.
What this covers
- Hot vs cold flows: why StateFlow/SharedFlow stay active in memory regardless of collectors
- StateFlow semantics: required initial value, conflation, holds latest, .value, distinctUntilChanged behaviour
- Conflation is why StateFlow is wrong for events: the same event emitted twice is delivered once
- A read-modify-write on .value is not atomic; update { } runs a compare-and-set loop instead
- SharedFlow configuration: replay, extraBufferCapacity, onBufferOverflow, emit vs tryEmit
- A default MutableSharedFlow drops emissions when nobody is subscribed
- subscriptionCount is itself a StateFlow, and is the mechanism WhileSubscribed is built on
- resetReplayCache clears replayed values, the workaround for a stale event surviving a rotation
- A Channel with receiveAsFlow buffers and delivers exactly once, but supports only one collector
- StateFlow versus LiveData: more operators and no Android dependency, but lifecycle awareness is no longer free
Study this topic
- StateFlow & SharedFlow explained: the guided lesson
- 17 practice quiz questions
- StateFlow & SharedFlow interview questions and answers