ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

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

Ioannis Anifantakis
ProAndroidDev
Published in
5 min readDec 8, 2024

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 UI reads it, that event is gone. No automatic replay, no old messages showing up again later.

Key Advantages:

  1. No Automatic Replay: Once the UI consumes the event, it disappears. You don’t need special logic to prevent “old” events from re-firing after a rotation.
  2. Easy Re-Emission: If you want to show the same toast message again later, just send it again. Each send() call is a fresh event. You don’t have to “reset” anything.
  3. Buffering with Channel.BUFFERED: Using Channel.BUFFERED gives your channel a small queue. If the UI isn’t ready to collect at the exact moment you send the event, that event is stored until the UI starts collecting. Without buffering, the producer may have to suspend until the consumer is ready, or events could be missed depending on the channel type.

Example Using a Channel to Show a Toast:

// In the ViewModel…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response