📱

Managing One-Time Events in Android

Jun 1, 2025

One-Time Events in Android

Key Concepts

  • ViewModel and UI: Events need to be sent from ViewModel to UI, executing only once.
  • Example: On a login screen, when the user logs in, a one-time navigation to the profile screen is needed.
  • Challenge: Event should not persist like state does, as it should not re-trigger after UI changes like screen rotation.

Opinions and Approaches

Manuel Vivo's Opinion

  • Suggests that one-off events are an anti-pattern.
  • Proposes modeling events as state using channels, flows, and state.

Channels vs Shared Flows vs State

  • Channels:
    • Events are sent once and have an integrated buffer.
    • Suitable for a single subscriber scenario.
  • Shared Flows:
    • Do not have a buffer by default; events can be lost if no collector is present.
    • Meant for multiple subscribers.
  • State:
    • Persistent, but requires resetting after receiving to avoid repeated actions.

Implementation

Using Channels

  • Create a channel to send navigation events.
  • Events can be collected safely using LaunchEffect and repeatOnLifecycle.
  • Events might be lost if sent when the UI is in a destroyed state.

Using Shared Flows

  • Similar to channels but without default buffering.
  • Buffer can be added by setting replay value.

Using State

  • Model events as state, updating state variable upon event.
  • Requires resetting state to avoid re-triggering upon navigation back.

Handling Event Loss

  • Events can be lost if sent when the UI is destroyed.
  • Use Dispatchers.Main.immediate to process events immediately in the same Android event cycle.
  • Demonstrates a workaround where events won't be lost using this dispatcher.

Conclusion and Recommendations

  • Channels: Recommended over shared flows for one-time UI events due to their single-subscriber nature.
  • State: Not preferred due to complexity in resetting state, leading to potential bugs.
  • Event loss is rare but can be prevented using dispatchers.

Additional Resources

  • Mentorship Program: Available for deeper problem-solving and codebase review.

Final Thoughts

  • Understanding one-time events in Android improves app stability and user experience.
  • Consider the trade-offs of each approach and choose based on the specific app requirements.

This video provides a comprehensive guide on handling one-time events on Android, exploring different methodologies and their implications.