Skip to content

Instantly share code, notes, and snippets.

@kaiyrzhanDE
Last active June 12, 2024 11:09
Show Gist options
  • Select an option

  • Save kaiyrzhanDE/64454879fcd00269200212a97ffbdfb5 to your computer and use it in GitHub Desktop.

Select an option

Save kaiyrzhanDE/64454879fcd00269200212a97ffbdfb5 to your computer and use it in GitHub Desktop.
Lifecycle In Jetpack Compose
@Composable
fun ComposableLifecycle(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
onEvent: (LifecycleOwner, Lifecycle.Event) -> Unit
) {
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { source, event ->
onEvent(source, event)
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
}
val TAG = "SecondScreen"
ComposableLifecycle { _, event ->
when (event) {
Lifecycle.Event.ON_CREATE -> {
Log.d(TAG, "onCreate")
}
Lifecycle.Event.ON_START -> {
Log.d(TAG, "On Start")
}
Lifecycle.Event.ON_RESUME -> {
Log.d(TAG, "On Resume")
}
Lifecycle.Event.ON_PAUSE -> {
Log.d(TAG, "On Pause")
}
Lifecycle.Event.ON_STOP -> {
Log.d(TAG, "On Stop")
}
Lifecycle.Event.ON_DESTROY -> {
Log.d(TAG, "On Destroy")
}
else -> {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment