Skip to content

Instantly share code, notes, and snippets.

@FireZenk
Created April 22, 2022 09:53
Show Gist options
  • Save FireZenk/4f00bb06da97faaa276fcfea3eeeafc8 to your computer and use it in GitHub Desktop.
Save FireZenk/4f00bb06da97faaa276fcfea3eeeafc8 to your computer and use it in GitHub Desktop.
Lifecycle event listener for Compose
@Composable
fun OnLifecycleEvent(onEvent: (owner: LifecycleOwner, event: Lifecycle.Event) -> Unit) {
val eventHandler = rememberUpdatedState(onEvent)
val lifecycleOwner = rememberUpdatedState(LocalLifecycleOwner.current)
DisposableEffect(lifecycleOwner.value) {
val lifecycle = lifecycleOwner.value.lifecycle
val observer = LifecycleEventObserver { owner, event ->
eventHandler.value(owner, event)
}
lifecycle.addObserver(observer)
onDispose {
lifecycle.removeObserver(observer)
}
}
}
OnLifecycleEvent { owner, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> TODO()
Lifecycle.Event.ON_CREATE -> TODO()
Lifecycle.Event.ON_START -> TODO()
Lifecycle.Event.ON_PAUSE -> TODO()
Lifecycle.Event.ON_STOP -> TODO()
Lifecycle.Event.ON_DESTROY -> TODO()
Lifecycle.Event.ON_ANY -> TODO()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment