Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@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