Last active
October 25, 2023 17:08
-
-
Save shahzadansari/f2e869139b97a058d37df1c236807c16 to your computer and use it in GitHub Desktop.
LifecycleObserver with DisposableEffect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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