Skip to content

Instantly share code, notes, and snippets.

@ksharma-xyz
Created May 12, 2024 11:00
Show Gist options
  • Save ksharma-xyz/c8027ecbb6df83aeaa379481c9d2f12a to your computer and use it in GitHub Desktop.
Save ksharma-xyz/c8027ecbb6df83aeaa379481c9d2f12a to your computer and use it in GitHub Desktop.
Listener for Composable Lifecycle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
@Composable
fun ComposableLifecycleListener(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
onEvent: (LifecycleOwner, Lifecycle.Event) -> Unit,
) {
DisposableEffect(key1 = lifecycleOwner) {
val observer = LifecycleEventObserver { source, event ->
onEvent(source, 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