StateFlow & SharedFlow Interview Questions

KOTLIN › Flow

What is the difference between StateFlow and SharedFlow?

What a strong answer covers: StateFlow is a hot flow that always holds exactly one current value: it needs an initial value, replays the latest value to new collectors, and skips values equal to the current one. SharedFlow is a configurable hot flow with no required value, adjustable replay and buffer, and it emits every value even if equal. StateFlow is for state; SharedFlow is for events or broadcasts.

StateFlow vs LiveData: why have many teams moved to StateFlow?

What a strong answer covers: Both hold a current value and are observable. StateFlow is pure Kotlin (testable without Android), has all Flow operators, requires an initial value, and works naturally with coroutines and in shared KMP code. LiveData is lifecycle-aware out of the box, which StateFlow needs repeatOnLifecycle or collectAsStateWithLifecycle to match. LiveData's postValue also conflates and its main-thread-only setValue is limiting.

How do you expose a StateFlow from a ViewModel without letting the UI modify it?

What a strong answer covers: Keep a private val _uiState = MutableStateFlow(UiState()) and expose val uiState: StateFlow<UiState> = _uiState.asStateFlow(). Update with _uiState.update { it.copy(...) }, which is atomic, rather than reading value and setting it, which can lose concurrent updates.

How do you handle one-off events like navigation or a snackbar? What are the trade-offs of SharedFlow, Channel and putting them in state?

What a strong answer covers: A SharedFlow with no replay drops events if nobody is collecting at that moment, for example during rotation. A Channel buffers until collected, but it's still lost if emitted after the collector stops and before it restarts, unless you collect on Main.immediate. Google's current guidance is to model events as state (an optional message in UiState) that the UI consumes and then tells the ViewModel it handled. A strong answer names the loss scenario for each.

StateFlow uses equality to skip emissions. What bugs can that cause, and what happens if you emit the same mutable object after changing it?

What a strong answer covers: StateFlow compares with equals and drops a new value equal to the current one. If you mutate a list inside the state and set the same object, nothing emits and the UI doesn't update. Two genuinely separate events with identical data (the same error twice) are merged into one. Fixes: always emit new immutable copies, include an id or timestamp for repeated events, or use SharedFlow for events. Fast updates are also conflated, so collectors only see the latest.

Back to StateFlow & SharedFlow