美文网首页
compose生命周期

compose生命周期

作者: yunhen | 来源:发表于2023-12-26 18:09 被阅读0次

/**
 *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)
        }
    }
}

相关文章

网友评论

      本文标题:compose生命周期

      本文链接:https://www.haomeiwen.com/subject/mvnbidtx.html