Created
May 12, 2024 11:00
-
-
Save ksharma-xyz/c8027ecbb6df83aeaa379481c9d2f12a to your computer and use it in GitHub Desktop.
Listener for Composable Lifecycle
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
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