One-off events done right
Why it matters
- A message or navigation flag in
UiStatethat nobody clears fires again after every rotation, becauseStateFlowgives its latest value to each new collector. - A
SharedFlow(replay = 0)drops events while nobody collects, and aChannelcan 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
UiStatethat 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
SharedFlowwithreplay = 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.
| Approach | While nobody collects | Can lose an event | Can repeat an event |
|---|---|---|---|
SharedFlow(replay = 0) | Dropped | Yes, whenever nobody collects | Yes, once per collector if there are several |
SharedFlow(replay = 1) | Last one kept | Yes, if a newer event overwrites it first | Yes, replayed to every new collector |
Channel with receiveAsFlow() | Buffered, or the sender suspends | Yes, if the collector is cancelled after receiving and before acting | No, each element goes to one collector |
Field in UiState, cleared by the UI | Kept in the ViewModel | No | Only 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.
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. StateFlowgives its latest value to every new collector. AshowToast = truethat 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
Channelbuffers 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. CallingconsumeEvent()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 aChannelnor aSharedFlowsurvives 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()
// }
// }updateonMutableStateFlowis 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.
nullis the idle state. This avoids the replay problem because afterconsumeEvent()the field isnulland the new collector after rotation seesnull. LaunchedEffect(state.event)keys on the event value. When it changes fromnullto a non-null event the effect runs; whenconsumeEvent()sets it back tonullthe effect re-runs but theletblock is a no-op.collectAsStateWithLifecycle(fromlifecycle-runtime-compose) stops collecting belowSTARTED. The event is not lost because theMutableStateFlowkeeps its value, and the UI acts on it when it comes back.- The
wheninside the effect handles UI work only. WithToastthe consume call runs right after; with a suspendingsnackbarHostState.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
- Users on a shopping app reported that a 'Item added to cart' toast appeared twice after rotating the phone.
- The team had a
showToast: Booleanfield inUiStateset totrueby the ViewModel. - On rotation the Composable was recreated, collected the
StateFlow, sawtrueagain, and showed the toast a second time. - The bug was invisible in testing because developers rarely rotate during a toast.
- The team replaced the boolean with a nullable
OneOffEvent?field and added aconsumeEvent()call in the ComposeLaunchedEffect. - They added a ViewModel unit test: after
addToCart()the event is set, and afterconsumeEvent()it isnull, 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.
- A checkout screen sent
NavEvent.ToConfirmationthrough aChannel(Channel.BUFFERED)after the order request finished on a background dispatcher. The Fragment collected it withreceiveAsFlow()insiderepeatOnLifecycle(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
Channelhad handed the event to the old collector, but the collector was cancelled by the rotation before thenavigatecall ran, so the event was gone. The buffer only protects events nobody has received yet.
- The team modelled the outcome as state:
UiState.placedOrderId: String?. The UI navigates when it is non-null and then callsviewModel.onNavigatedToConfirmation(), which sets it back tonull. - 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)
-
Open your project's main
ViewModelthat exposes aStateFlow<UiState>. Add a sealed interfaceOneOffEventwith two variants:ShowMessage(msg: String)andNavigate(route: String). -
Add a nullable field
event: OneOffEvent? = nullto yourUiStatedata class. Do not add any other fields. -
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. -
Add a
fun consumeEvent()to the ViewModel that calls_uiState.update { it.copy(event = null) }. -
In the Compose screen that collects the state, add a
LaunchedEffect(state.event)block. Inside, usestate.event?.let { ... }to act on the event (show aToastor callnavController.navigate), then callviewModel.consumeEvent(). -
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().