observeEvent

inline fun <T> LifecycleOwner.observeEvent(liveData: LiveData<OneTimeEvent<T>>, crossinline action: (T) -> Unit)(source)

Observes a LiveData containing OneTimeEvents and consumes unhandled events.

Consumption is at most once per OneTimeEvent instance. The content is marked consumed before action runs; an exception in the action does not make the event available again. A newly created event has its own consumption flag, and the flag is not persisted across process death. This helper does not acknowledge completed navigation or snackbar display.

Illustrative Fragment excerpt; ViewModel, binding, and Material Snackbar imports are omitted. Register in onViewCreated with the view's lifecycle owner:

viewLifecycleOwner.observeEvent(viewModel.snackbarMessage) { message ->
Snackbar.make(binding.root, message, Snackbar.LENGTH_SHORT).show()
}

Parameters

liveData

LiveData containing OneTimeEvents

action

Callback invoked with unhandled event content

Type Parameters

T

The type of event data

See also


inline fun <T> LifecycleOwner.observeEvent(liveData: MutableLiveData<OneTimeEvent<T>>, crossinline action: (T) -> Unit)(source)

Observes a MutableLiveData containing OneTimeEvents and consumes unhandled events.

This is an overload of observeEvent for MutableLiveData. Functionally identical to the LiveData variant but accepts MutableLiveData directly.

Parameters

liveData

MutableLiveData containing OneTimeEvents

action

Callback invoked with unhandled event content

Type Parameters

T

The type of event data

See also