StateFlow & SharedFlow
KOTLIN › Concurrency
Hot Kotlin flows for UI state versus one-off events, collected lifecycle-safely.
Interviewers use StateFlow and SharedFlow to test whether you can model UI state separately from one-time events and collect both without leaking work or crashing. Expect to defend why StateFlow needs an initial value and conflates, why SharedFlow fits navigation and snackbar events, and how repeatOnLifecycle / collectAsStateWithLifecycle replace the discouraged launchWhenStarted. It is a frequent staff-level discriminator because the wrong choice causes lost events, duplicate dialogs, or wasted background work.
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 behavior
- SharedFlow configuration: replay, extraBufferCapacity, onBufferOverflow, emit vs tryEmit
- Choosing state vs events: StateFlow for UI state, SharedFlow for navigation/snackbar one-offs
- Safe collection: repeatOnLifecycle(STARTED) and collectAsStateWithLifecycle
- Why launchWhenStarted/launchWhenResumed are discouraged and how stateIn/WhileSubscribed help
Study this topic
- StateFlow & SharedFlow explained: the guided lesson
- 14 practice quiz questions
- 9 revision flashcards
- StateFlow & SharedFlow interview questions and answers