LifecycleEventEffect

Functions summary

Unit
@Composable
LifecycleEventEffect(
    event: Lifecycle.Event,
    lifecycleOwner: LifecycleOwner,
    onEvent: () -> Unit
)

Schedule an effect to run when the Lifecycle receives a specific Lifecycle.Event.

Cmn

Functions

LifecycleEventEffect

@Composable
fun LifecycleEventEffect(
    event: Lifecycle.Event,
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    onEvent: () -> Unit
): Unit

Schedule an effect to run when the Lifecycle receives a specific Lifecycle.Event.

Using a LifecycleEventObserver to listen for when LifecycleEventEffect enters the composition, onEvent will be launched when receiving the specified event.

This function should not be used to listen for Lifecycle.Event.ON_DESTROY because Compose stops recomposing after receiving a Lifecycle.Event.ON_STOP and will never be aware of an ON_DESTROY to launch onEvent.

This function should also not be used to launch tasks in response to callback events by way of storing callback data as a Lifecycle.State in a MutableState. Instead, see currentStateAsState to obtain a State that may be used to launch jobs in response to state changes.

import androidx.compose.runtime.Composable
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect

@Composable
fun Analytics(dataAnalytics: DataAnalytics) {
    LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { dataAnalytics.trackScreenView("screen1") }

    // ...
}
Parameters
event: Lifecycle.Event

The Lifecycle.Event to listen for

lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current

The lifecycle owner to attach an observer

onEvent: () -> Unit

The effect to be launched when we receive an event callback

Throws
IllegalArgumentException

if attempting to listen for Lifecycle.Event.ON_DESTROY