One-off events done right

Learn why Android's guidance models one-off events as UI state the UI acknowledges, and how a SharedFlow or Channel can lose or repeat an event. About 25 minutes.

Why it matters

  • A message or navigation flag in UiState that nobody clears fires again after every rotation, because StateFlow gives its latest value to each new collector.
  • A SharedFlow(replay = 0) drops events while nobody collects, and a Channel can lose an event that a collector received just before it was cancelled. Both bugs are intermittent and hard to reproduce.
  • Interviewers ask this because it separates developers who copy a pattern from those who know exactly where each approach loses or repeats an event.
  • In MVI the same question becomes: where does the event live in the single state, and which intent clears it.

The simple explanation

  • A restaurant whiteboard shows the current table status: seated, ordering, eating. That is state.
  • A note that says 'bring the check' is a one-off action, not a status.
  • If you write the note on the whiteboard and nobody wipes it, every waiter who looks brings the check again. That is a flag in UiState that is never cleared.
  • If the waiter who acts on it wipes it off, it is done exactly once, and a new waiter starting a shift still sees it if nobody has acted yet. That is state the UI acknowledges.
  • If you shout it across the room and no waiter is listening, it is gone. That is a SharedFlow with replay = 0.

A one-off event is something the UI does once: show a snackbar, navigate, open a dialog. Google's architecture guidance says events that come from the ViewModel should always become a UI state update. Do not ask "what should the UI do?"; ask "how does this change the UI state?" A failed save becomes userMessage = "Could not save"; a successful login becomes isUserLoggedIn = true, and the UI navigates when it sees it.

The UI notifies the ViewModel once it has acted, for example userMessageShown(), and the ViewModel clears the field. Because the MutableStateFlow lives in the ViewModel, the event survives rotation; because the UI clears it explicitly, it fires once. Events that start in the UI and need no business logic, such as tapping a Help button, do not go through the ViewModel at all: the UI navigates directly.

ApproachWhile nobody collectsCan lose an eventCan repeat an event
SharedFlow(replay = 0)DroppedYes, whenever nobody collectsYes, once per collector if there are several
SharedFlow(replay = 1)Last one keptYes, if a newer event overwrites it firstYes, replayed to every new collector
Channel with receiveAsFlow()Buffered, or the sender suspendsYes, if the collector is cancelled after receiving and before actingNo, each element goes to one collector
Field in UiState, cleared by the UIKept in the ViewModelNoOnly if the UI never clears it

The Channel loss window is small but real. When the event is sent from a background thread, the collector is resumed on the main thread a moment later. If the lifecycle drops below STARTED in between (rotation, the app going to the background), the collector is cancelled, and the element it already took from the channel is gone. Collecting on Dispatchers.Main.immediate and sending from the main thread narrows the window, but it is still harder to test than plain state.

In MVI the same idea applies: the reducer sets the event field, the UI acts on it and sends an intent such as MessageShown, and the reducer clears it. Consumption is a state transition, so it is covered by reducer tests.

A one-off message kept as state
A one-off message kept as state The ViewModel puts the message in the userMessage field of its UiState. The UI collects the state and shows a snackbar for it, then calls userMessageShown. The ViewModel clears the field to null, so the snackbar is not shown again. Because the field lives in the ViewModel, a rotation in between does not lose it. A rotation before userMessageShown keeps the message SET userMessage UiState(userMessage) SHOW SNACKBAR userMessageShown() userMessage = null UiState, NO MESSAGE ViewModel holds UiState UI shows a snackbar
The message lives in the UiState until the UI reports it shown, so it is not lost on rotation and appears only once.

Notes

  • Google's guidance: ViewModel events should become UI state. Think about how the event changes the state (userMessage, isUserLoggedIn), not about what the UI should do.
  • StateFlow gives its latest value to every new collector. A showToast = true that nobody clears fires again after every configuration change.
  • The pattern: a nullable field in UiState. The UI acts on it, then calls the ViewModel (consumeEvent(), userMessageShown()) to set it back to null.
  • SharedFlow(replay = 0) drops events emitted while nobody collects: during a rotation, or while the app is in the background with lifecycle-aware collection.
  • A Channel buffers events while nobody collects (or suspends the sender), so the gap itself does not lose them. It loses one when the collector is cancelled after receiving and before acting.
  • A single nullable field holds only one event. If two arrive before the UI acts, the first is overwritten. Keep a list in state, give each item an id, and remove it by id after it is shown.
  • LaunchedEffect(state.event) restarts when the event value changes. Calling consumeEvent() at the end of the block sets the field to null; the effect restarts with null and does nothing.
  • Events that start in the UI and need no business logic (tap Help, open a link) are handled in the UI directly; there is nothing to send through the ViewModel.
  • Test the consume path: assert the event is set after the action and null after consumeEvent(). A test that only checks it was set passes even if it is never cleared.
  • The field survives rotation because the ViewModel does. It survives process death only if you also save it with SavedStateHandle; neither a Channel nor a SharedFlow survives process death.

Code example

This shows the consumed-state pattern in a ViewModel: a sealed OneOffEvent interface, a nullable event field in UiState, an atomic update that sets both state and event, and a consumeEvent function the UI calls after acting. The Compose side is shown as comments for reference.

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
 
// One-off events as state in UiState that the UI acknowledges
 
sealed interface OneOffEvent {
    data class ShowToast(val msg: String) : OneOffEvent
    data class Navigate(val route: String) : OneOffEvent
}
 
data class UiState(
    val items: List<String> = emptyList(),
    val event: OneOffEvent? = null, // null means nothing pending
)
 
class ItemsViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(UiState())
    val uiState: StateFlow<UiState> = _uiState.asStateFlow()
 
    fun onItemClicked(item: String) {
        // Update state and set the one-off event atomically
        _uiState.update {
            it.copy(
                items = it.items + item,
                event = OneOffEvent.ShowToast("Added: " + item),
            )
        }
    }
 
    // UI calls this after acting on the event
    fun consumeEvent() {
        _uiState.update { it.copy(event = null) }
    }
}
 
// Compose side (reference only):
// val state by viewModel.uiState.collectAsStateWithLifecycle()
// LaunchedEffect(state.event) {
//     state.event?.let {
//         when (it) {
//             is OneOffEvent.ShowToast -> Toast.makeText(ctx, it.msg, Toast.LENGTH_SHORT).show()
//             is OneOffEvent.Navigate -> navController.navigate(it.route)
//         }
//         viewModel.consumeEvent()
//     }
// }
  • update on MutableStateFlow is atomic: the lambda reads the current value and writes the new one without a race. Both the state change and the event are set in one emission.
  • The event field is nullable. null is the idle state. This avoids the replay problem because after consumeEvent() the field is null and the new collector after rotation sees null.
  • LaunchedEffect(state.event) keys on the event value. When it changes from null to a non-null event the effect runs; when consumeEvent() sets it back to null the effect re-runs but the let block is a no-op.
  • collectAsStateWithLifecycle (from lifecycle-runtime-compose) stops collecting below STARTED. The event is not lost because the MutableStateFlow keeps its value, and the UI acts on it when it comes back.
  • The when inside the effect handles UI work only. With Toast the consume call runs right after; with a suspending snackbarHostState.showSnackbar(...), a cancellation before the consume call means the message shows again later, which is better than losing it.

Run the idea in plain Kotlin

A single nullable field overwrites an event that arrives before the UI acts. A list of messages with ids keeps both, and an acknowledged message never comes back, even after a simulated rotation.

data class Message(val id: Long, val text: String)

data class UiState(
  val items: List<String> = emptyList(),
  val pendingEvent: String? = null,
  val messages: List<Message> = emptyList(),
)

class SingleFieldStore {
  var state = UiState()
      private set

  fun addItem(item: String) {
      state = state.copy(items = state.items + item, pendingEvent = "Added: " + item)
  }

  fun consumeEvent() {
      state = state.copy(pendingEvent = null)
  }
}

class QueueStore {
  var state = UiState()
      private set
  private var nextId = 1L

  fun addItem(item: String) {
      val message = Message(nextId++, "Added: " + item)
      state = state.copy(items = state.items + item, messages = state.messages + message)
  }

  fun messageShown(id: Long) {
      state = state.copy(messages = state.messages.filterNot { it.id == id })
  }
}

fun main() {
  val single = SingleFieldStore()
  single.addItem("apple")
  single.addItem("banana") // arrives before the UI acts
  println("Single field, UI sees: " + single.state.pendingEvent)
  single.consumeEvent()
  println("Single field after consume: " + single.state.pendingEvent)

  val queue = QueueStore()
  queue.addItem("apple")
  queue.addItem("banana")
  println("Queue, pending: " + queue.state.messages.map { it.text })
  val first = queue.state.messages.first()
  println("UI shows '" + first.text + "' and acknowledges id " + first.id)
  queue.messageShown(first.id)
  // Rotation: a new UI reads the same state from the ViewModel
  println("After rotation, pending: " + queue.state.messages.map { it.text })
  val second = queue.state.messages.first()
  println("UI shows '" + second.text + "' and acknowledges id " + second.id)
  queue.messageShown(second.id)
  println("Pending now: " + queue.state.messages + ", items: " + queue.state.items)
}

Expected output:

Single field, UI sees: Added: banana
Single field after consume: null
Queue, pending: [Added: apple, Added: banana]
UI shows 'Added: apple' and acknowledges id 1
After rotation, pending: [Added: banana]
UI shows 'Added: banana' and acknowledges id 2
Pending now: [], items: [apple, banana]

In production

Toast fires twice after rotation
  • Users on a shopping app reported that a 'Item added to cart' toast appeared twice after rotating the phone.
  • The team had a showToast: Boolean field in UiState set to true by the ViewModel.
  • On rotation the Composable was recreated, collected the StateFlow, saw true again, and showed the toast a second time.
  • The bug was invisible in testing because developers rarely rotate during a toast.
The fix
  • The team replaced the boolean with a nullable OneOffEvent? field and added a consumeEvent() call in the Compose LaunchedEffect.
  • They added a ViewModel unit test: after addToCart() the event is set, and after consumeEvent() it is null, so a new collector after rotation has nothing to act on.
  • The same check runs for every screen that sets an event, so a missing consume call fails a test instead of reaching users.
Navigation lost during rotation
  • A checkout screen sent NavEvent.ToConfirmation through a Channel(Channel.BUFFERED) after the order request finished on a background dispatcher. The Fragment collected it with receiveAsFlow() inside repeatOnLifecycle(STARTED).
  • A few users who rotated the phone right as the order completed stayed on the checkout screen, even though the order had been placed.
  • The Channel had handed the event to the old collector, but the collector was cancelled by the rotation before the navigate call ran, so the event was gone. The buffer only protects events nobody has received yet.
The fix
  • The team modelled the outcome as state: UiState.placedOrderId: String?. The UI navigates when it is non-null and then calls viewModel.onNavigatedToConfirmation(), which sets it back to null.
  • Because the field lives in the ViewModel, a rotation at any moment leaves it in place until the new UI acts on it.
  • A ViewModel test asserts the field is set after the order succeeds and cleared after the acknowledgement call.

Common mistakes

  • Setting a flag in UiState and never clearing it. StateFlow gives its latest value to every new collector, so after rotation the action fires again. Keep the event in state, but have the UI call the ViewModel to clear it after acting.
  • Assuming a Channel cannot lose events. It buffers events nobody has received yet, but an event received by a collector that is cancelled before it acts is lost. Prefer state the UI acknowledges.
  • Forgetting to call consumeEvent() after acting on the event. The event stays non-null in the state. The next recomposition or a new collector will act on it again, causing a duplicate toast or double navigation. Clear the field at the end of the same effect block.
  • Using SharedFlow with replay = 1 for one-off events. The last event is replayed to every new collector, so after rotation it fires again. With replay = 0 it is dropped while nobody collects instead. Prefer state.
  • Handling the event inside the ViewModel instead of the UI. The ViewModel should not call Toast.makeText or navigate. It puts the event into state; the UI acts on it. This keeps the ViewModel testable and free of Android UI dependencies.
  • Sending UI-only events through the ViewModel. A tap on Help that needs no business logic can navigate directly in the UI. Routing it through the ViewModel adds a round trip and a place to lose it.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How do you handle one-off events like toasts or navigation in MVVM?”

“When would you choose a Channel over a state field for one-off events?”

“What is the difference between SharedFlow with replay = 0 and a Channel for one-off events?”

“How do you test a one-off event in a ViewModel?”

Quiz

What happens when a new collector subscribes to a StateFlow whose latest value has showToast = true?

Which of these drops a one-off event emitted during a rotation, when no collector is active?

In the state-based pattern, what does the UI do after acting on a one-off event?

In MVI, where does a one-off event such as a user message live?

0 of 4 answered

Mini task

Add a one-off event to an existing ViewModel (15 min)

  1. Open your project's main ViewModel that exposes a StateFlow<UiState>. Add a sealed interface OneOffEvent with two variants: ShowMessage(msg: String) and Navigate(route: String).

  2. Add a nullable field event: OneOffEvent? = null to your UiState data class. Do not add any other fields.

  3. In the ViewModel, find the function that triggers a user-visible action (for example, a submit or a click handler). Inside that function, use _uiState.update { it.copy(event = OneOffEvent.ShowMessage("Done")) } to set the event atomically alongside any state change.

  4. Add a fun consumeEvent() to the ViewModel that calls _uiState.update { it.copy(event = null) }.

  5. In the Compose screen that collects the state, add a LaunchedEffect(state.event) block. Inside, use state.event?.let { ... } to act on the event (show a Toast or call navController.navigate), then call viewModel.consumeEvent().

  6. Run the app. Trigger the action. Rotate the device. Confirm the toast or navigation fires exactly once, not twice.

Done condition: After rotation the event does not re-fire. A unit test passes that asserts the event is set after the action and null after consumeEvent().

Next: Room: entities, DAOs, queries