Composable曝光和反曝光实现

1、Composable曝光和反曝光实现

在Compose开发过程中,需要在进入退出重组以及View可见的场景进行@Composable的曝光和反曝光,进入退出重组的话可以通过LaunchedEffect和DisposableEffect来监听,那View可见的场景就得通过Lifecycle来实现了,如下所示,可以统一在DisposableEffect里面通过生命周期监听来处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Composable
inline fun ReportWithLifecycle(noinline onImpl: () -> Unit,
noinline onImplEnd: () -> Unit,
content: @Composable () -> Unit) {
// 使用rememberUpdatedState保证在不重启DisposableEffect情况下使用最新的参数
val currentOnImpl by rememberUpdatedState(onImpl)
val currentOnImplEnd by rememberUpdatedState(onImplEnd)

val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
//曝光
currentOnImpl()
} else if (event == Lifecycle.Event.ON_PAUSE) {
//反曝光
currentOnImplEnd()
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
//反曝光
currentOnImplEnd()
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
content()
}

2、使用方式

1
2
3
4
5
6
7
8
9
10
11
Report {
Text(
modifier = Modifier.fillMaxHeight(),
textAlign = TextAlign.Center,
overflow = TextOverflow.Ellipsis,
fontSize = 16.sp,
color = Color.White,
maxLines = 1,
fontWeight = FontWeight(500),
text = text)
}

使用Report包起来,就自动实现了这个Text的曝光和反曝光逻辑