After a rotation, a LiveData-driven order-tracking screen shows its 'Order cancelled' snackbar again; why does LiveData redeliver it, and how do you fix it?
answer
- state holder, not event bus
- new observer starts behind
- handled-flag wrappers, and their limits
- turn the event into UI state
basics
~20 sLiveData keeps its last value and delivers it to every new observer once started, so the recreated activity shows the message again. Handled-flag event wrappers were the old fix; today the message is UI state the ViewModel clears once shown.
solid answer
~50 sLiveData is a state holder: each observer tracks the last version it saw, and a newly registered one starts from nothing, so once the recreated activity is `STARTED` it receives the current value, the stored "Order cancelled" message, and shows the snackbar again. The same replay happens when a fragment returns from the back stack. The old fix wrapped each event in a class with a handled flag so a second read did nothing, but the flag is shared between observers and it does not stop LiveData from losing events, since inactive observers get only the latest value and rapid `postValue` calls collapse. Current guidance is to process the event in the ViewModel and expose it as UI state, such as a pending message the UI shows and then reports as shown so the ViewModel clears it.
code
kotlin · 13 linesdata class TrackingUiState(
val status: OrderStatus? = null,
val pendingMessage: String? = null,
)
// In the activity, after the ViewModel exposes uiState as LiveData:
viewModel.uiState.observe(this) { state ->
statusView.text = state.status?.label
state.pendingMessage?.let { message ->
Snackbar.make(root, message, Snackbar.LENGTH_SHORT).show()
viewModel.onMessageShown() // the ViewModel clears pendingMessage
}
}go deeper
Recall that a new observer receives the LiveData's current value as soon as its screen is started.
Explain how rotation creates a new observer that is behind the LiveData, so the stored value is delivered again.
Diagnose replayed snackbars or navigations as an event stored as state, name the wrapper's limits, and model the event as UI state instead.
Set the team convention for one-off UI effects so every screen handles rotation, multiple observers and lost events the same way.
## LiveData holds state, not events `LiveData` keeps one current value and makes sure every observer, once active, sees it. That is the right contract for **state**, such as an order's status or a list of orders, and the wrong one for an **event**: something that should happen once, such as showing an "Order cancelled" snackbar or navigating to a receipt. ## Why the snackbar appears again Internally, LiveData counts how many times its value has been set, and each observer remembers the count it last saw. A newly registered observer starts from "has seen nothing", so as soon as its owner is `STARTED`, LiveData hands it the current value. Walk through a rotation: 1. The ViewModel sets its message LiveData to "Order cancelled", and the activity's observer shows a snackbar. 2. The user rotates the device. The old activity is destroyed and its observer removed; the ViewModel, and the LiveData inside it, survive. 3. The new activity calls `observe` in `onCreate`. When it starts, its new observer is behind the LiveData's count, so it receives "Order cancelled" and shows the snackbar a second time. The same replay happens when a fragment returns from the back stack and observes with a new view lifecycle owner, and for any second screen that observes the same LiveData later. Nothing is broken: the LiveData guide documents that a recreated activity immediately receives the latest available data. The design simply stored an event as state. ## LiveData can also lose events The opposite failure exists too, which makes LiveData doubly unfit for events: - While an observer is inactive, only the **latest** value is delivered when it becomes active again. Two events set while the app is in the background arrive as one. - `postValue` keeps one pending slot. Two events posted from a background thread before the main thread runs collapse into the second, and the first never reaches anyone. ## The old fix: event wrappers For years, teams wrapped each event in a small class holding the payload and a "has been handled" flag. The observer read the content only if it had not been handled yet, then set the flag. Rotation still redelivered the wrapper, but the new observer saw it was handled and did nothing. A variant subclassed `MutableLiveData` so that only one observer received each value. These were workarounds with known costs: - The handled flag is shared, so with two observers only the first one to read it gets the event. - They did nothing about the coalescing described above. - Consumption happened inside the UI, invisible to the ViewModel and hard to assert in tests. ## The current fix: model the event as state Android's architecture recommendations say not to send events from the ViewModel to the UI: process the event in the ViewModel and turn its result into a state update. For the snackbar: 1. The screen's UI state gains a field for a pending message, null when there is none. 2. The ViewModel sets that field when the order is cancelled. 3. The UI shows the snackbar while the field is set, then tells the ViewModel the message was shown, and the ViewModel clears the field. Rotation now replays a state that is still true. If the message was not yet shown it should still appear, and once it is cleared the new activity sees nothing to show. Navigation works the same way: the state records that the order was cancelled, and the UI decides where to go. | approach | after rotation | with two observers | |---|---|---| | event stored as a plain LiveData value | shown again | both react | | wrapper with a handled flag | ignored | only the first reacts | | event modelled as state, cleared by the ViewModel | shown only if still pending | both see the same state | ## How to spot the bug in review - A LiveData whose name is a verb or an instruction (show, navigate, open) rather than a noun describing state. - Observers that call `Toast`, `Snackbar` or navigation directly from `onChanged`. - Bug reports that mention rotation, dark-mode switches or returning from another screen.
- Besides rotation, when else does a LiveData observer receive a value that was set before it registered?Whenever a new observer registers and its owner reaches STARTED: a fragment returning from the back stack observes again with a new view lifecycle owner, a second screen observes a shared LiveData, or a dialog observes the same ViewModel later. Each one receives the current value once.
- Why can two one-off events sent through LiveData arrive as one, or be lost?LiveData delivers only the latest value when an observer becomes active, so two events set while the screen is stopped reach it as one. And postValue keeps a single pending slot, so two events posted from a background thread before the main thread runs collapse into the second.
LiveData is a whiteboard in a shared office, not a doorbell. Anyone who walks in reads whatever is written there, however long ago it was written, so a message meant for one moment should be wiped once someone has acted on it.
- The snackbar repeats because the ViewModel calls setValue again after rotation.
- The value comes back from the activity's saved instance state Bundle.
- LiveData replays a buffer of recent values to each new observer.
- An event wrapper with a handled flag works correctly with any number of observers.
- Moving the event to postValue stops it from being redelivered after rotation.