Member-only story
Handling One-Time Events in Jetpack Compose: Channels vs. SharedFlow

In Jetpack Compose, you’ll often deal with “one-time” events — ephemeral actions like navigating to a new screen or showing a toast message once. These aren’t ongoing states you want to continuously observe; they’re moment-in-time signals that should occur once and then vanish.
Two popular tools for delivering events from your ViewModel to the UI are Channels and SharedFlow. While both can emit values, they differ in fundamental ways. Channels naturally align with one-time events, while SharedFlow is more suited for continuous, shared data streams.
Understanding One-Time Events
A one-time event is something like:
- Navigation: After a network call completes, navigate to a detail screen just once.
- Toast Messages: Show a “Hello!” toast after a button click and don’t repeat it unless explicitly triggered again.
The challenge lies in ensuring these events happen exactly once. After a screen rotation or returning to a screen, you don’t want old events replaying themselves.
Why Channels Are Ideal for One-Time Events
A Kotlin Channel
works like a one-way mailbox. You send an event from the ViewModel, and once the…