Skip to content

Instantly share code, notes, and snippets.

@shahzadansari
Last active October 25, 2023 17:08
Show Gist options
  • Save shahzadansari/f2e869139b97a058d37df1c236807c16 to your computer and use it in GitHub Desktop.
Save shahzadansari/f2e869139b97a058d37df1c236807c16 to your computer and use it in GitHub Desktop.
LifecycleObserver with DisposableEffect
@Composable
fun Screen() {
LifecycleObserver { event ->
if (event == Lifecycle.Event.ON_RESUME) {
// doSomething()
}
}
}
/** Inspired by: https://medium.com/@mohammadjoumani/life-cycle-in-jetpack-compose-2e96136ab936 **/
@Composable
fun LifecycleObserver(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
onEvent: (event: Lifecycle.Event) -> Unit
) {
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
onEvent(event)
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment