how to detect app lifecycle events on a jetpack compose composable

In order to detect app lifecycle events ( onPause, onStop, onResume ) in a jetpack compose composable i come up with this function :

fun rememberLifecycleEvent(lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current): Lifecycle.Event {
var state by remember { mutableStateOf(Lifecycle.Event.ON_ANY) }
DisposableEffect(lifecycleOwner) {
    val observer = LifecycleEventObserver { _, event ->
        Log.v("log", "event  : $event")

        state = event
    }
    lifecycleOwner.lifecycle.addObserver(observer)
    onDispose {
        lifecycleOwner.lifecycle.removeObserver(observer)
    }
}
Log.v("log", "$state")

return state
}

and then inside my composable i am using it like this :

val lifecycleEvent = rememberLifecycleEvent()

    LaunchedEffect(lifecycleEvent) {

        when (lifecycleEvent) {

            Lifecycle.Event.ON_START -> {
                // code here
            }

            Lifecycle.Event.ON_RESUME -> {
               // code here
            }

            else -> {}
        }
    }

my problem is that i noticed that this is not very consistent, by that i mean sometimes i don’t receive the onStart which is so strange because i see it in the event log, but not in the returned state, there’s must be something to do with the mutableState of state ,but can’t find out what is the issue

Leave a Comment