ObserveAsEvents

fun <T> ObserveAsEvents(flow: Flow<T>, key1: Any? = null, key2: Any? = null, minActiveState: Lifecycle.State = Lifecycle.State.STARTED, onEvent: (T) -> Unit)

Observes a Flow and executes the onEvent callback for each emitted value in a lifecycle-aware manner.

Uses LaunchedEffect and repeatOnLifecycle to ensure flow collection occurs only when the composable's lifecycle is at least in minActiveState (defaults to Lifecycle.State.STARTED).

Employs rememberUpdatedState so that onEvent always invokes the most recent lambda instance across recompositions without restarting the underlying flow collection.

Parameters

flow

The Flow to observe.

key1

An optional key that, if changed, will restart flow collection.

key2

Another optional key that, if changed, will restart flow collection.

minActiveState

The minimum Lifecycle.State required to collect events. Defaults to Lifecycle.State.STARTED.

onEvent

Callback invoked for each value emitted by flow.

Type Parameters

T

The type of data emitted by the Flow.


@JvmName(name = "ObserveAsEventsFromFlow")
fun <T> Flow<T>.ObserveAsEvents(key1: Any? = null, key2: Any? = null, minActiveState: Lifecycle.State = Lifecycle.State.STARTED, onEvent: (T) -> Unit)

Extension function variant of ObserveAsEvents for convenient fluent syntax.

Example:

viewModel.uiEvent.ObserveAsEvents { event ->
when (event) { ... }
}