StateFlow & SharedFlow Interview Questions

KOTLIN › Concurrency

You use a SharedFlow with no replay for one-time navigation events, but the collector isn't actively subscribed yet, say during a process-death restore or before the UI has finished setting up its collection. Walk me through what happens to that event.

What a strong answer covers: With replay set to zero, a SharedFlow only delivers a value to collectors that are actively subscribed at the moment of emission, so if nothing is collecting yet the event is simply gone, there's no buffering to catch it later. This is precisely why SharedFlow-based navigation events need collection wired up early and reliably (repeatOnLifecycle) and why some teams accept a small replay or a different pattern for events that must survive a brief gap in collection.

Your team debates whether snackbar and toast events should be a StateFlow wrapped in an Event/consumed-flag class, or a plain SharedFlow. What are the actual trade-offs, and which would you pick?

What a strong answer covers: The Event-wrapped StateFlow approach reuses a familiar type and survives configuration changes trivially since it's just state, but it requires a manual 'has this been consumed' flag and is easy to get wrong with multiple collectors each independently consuming or missing the flag toggle. A plain SharedFlow with no replay models one-off events honestly, since it's not really state, but it demands collection be live and correctly scoped or events are silently dropped; most teams converge on SharedFlow now specifically because it matches the semantics of the problem rather than repurposing state to fake an event.

You're modeling a chat screen: the message list, a typing indicator, and a 'new message arrived, scroll to bottom' signal. How would you decide which of these becomes StateFlow versus SharedFlow, and is there a case here where neither cleanly fits?

What a strong answer covers: The message list and typing indicator are naturally StateFlow, they represent 'what is true right now' that a late subscriber should immediately see and that's fine to conflate. The scroll-to-bottom signal is closer to a SharedFlow event since replaying a stale scroll command to a late subscriber would be wrong, but it also arguably wants to correlate with a specific message, so a strong answer notes that sometimes the cleanest model is folding the signal into the state itself, for example a lastMessageId the UI diffs against, rather than forcing a separate one-off event channel for it.

Back to StateFlow & SharedFlow