/**
*DisposableEffect :效应 (需要清理的效应)
*/
@Composable
fun HomeScreenCreate(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
onCreate: () -> Unit, // Send the 'started' analytics event
onDestroy: () -> Unit // Send the 'stopped' analytics event
){
// Safely update the current lambdas when a new one is provided
val currentOnCreate by rememberUpdatedState(onCreate)
val currentOnDestroy by rememberUpdatedState(onDestroy)
// 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_CREATE) {
currentOnCreate()
} else if (event == Lifecycle.Event.ON_DESTROY) {
currentOnDestroy()
}
}
// Add the observer to the lifecycle
lifecycleOwner.lifecycle.addObserver(observer)
// When the effect leaves the Composition, remove the observer
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
}
网友评论