Skip to content

Instantly share code, notes, and snippets.

@saqib-github-commits
Created May 17, 2023 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saqib-github-commits/9639971eb9e63be4e331f5e7921aaf24 to your computer and use it in GitHub Desktop.
Save saqib-github-commits/9639971eb9e63be4e331f5e7921aaf24 to your computer and use it in GitHub Desktop.
@Composable
fun DisposableEffectScreen(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
viewModel: DisposableEffectViewModel
) {
val logOnResume by rememberUpdatedState(newValue = { viewModel.logViewEvent() })
// If `lifecycleOwner` changes, dispose and reset the effect
DisposableEffect(lifecycleOwner) {
// Create an observer that triggers our remembered callbacks
// for sending analytics events
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
logOnResume()
}
}
// Add the observer to the lifecycle
lifecycleOwner.lifecycle.addObserver(observer)
// When the effect leaves the Composition, remove the observer
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
// Content of page
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment