Jetpack Compose中Compose的生命周期

前言

Jetpack Compose 中,并没有传统 Android View 系统中的 onCreate()onStart()onResume() 等生命周期方法。取而代之的是,Compose 通过 可组合函数(Composable functions) 的执行机制和 状态驱动的 UI 更新模型 来管理 UI 的“生命周期”。

不过,Compose 提供了一些与 宿主 Activity/Fragment 生命周期 集成的机制,以及一些用于监听 组合(Composition)生命周期 的工具。

Compose 本身的“组合生命周期”

每个可组合函数在被调用时会经历以下阶段:

  1. Enter the Composition(进入组合)
  • 当某个 Composable 首次被调用并需要渲染时,它会被加入到 Composition(组合) 中。
  • 这类似于 View 的 onAttachedToWindow()
  1. Recomposition(重组)
  • 当 Composable 所依赖的状态(State)发生变化时,Compose 会重新执行该 Composable(及其子项),这个过程称为 Recomposition
  • 只有受影响的部分会被重组,其余部分保持不变(得益于智能重组机制)。
  1. Leave the Composition(离开组合)
  • 当 Composable 不再需要显示(例如条件为 false、导航离开等),它会从 Composition 中移除。
  • 类似于 View 的 onDetachedFromWindow()

Compose的生命周期事件

LaunchedEffect / DisposableEffect / SideEffect

这些是 Compose 提供的副作用(Side-effect)API,用于在特定时机执行逻辑:

LaunchedEffect(key)

  • 在进入组合时启动一个协程。
  • 当 key 改变时,取消旧的协程并启动新的。
  • 离开组合时自动取消。
1
2
3
4
5
6
7
@Composable
fun MyScreen() {
LaunchedEffect(Unit) {
// 进入组合时执行(类似 onCreate)
println("Entered composition")
}
}

DisposableEffect(key)

  • 在进入组合时执行初始化代码,在离开组合或 key 改变时执行清理代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Composable
fun MyScreen(lifecycleOwner: LifecycleOwner) {
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> { /* ... */ }
Lifecycle.Event.ON_PAUSE -> { /* ... */ }
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
}

SideEffect

  • 每次重组后执行,用于同步 Compose 状态到非 Compose 世界(如第三方库)。
1
2
3
4
5
6
7
@Composable
fun MyComponent(analytics: Analytics) {
var userId by remember { mutableStateOf("") }
SideEffect {
analytics.setUser(userId)
}
}

与Android组件生命周期集成

虽然 Compose 本身没有生命周期,但它运行在 Activity/Fragment 中,因此可以监听宿主的生命周期:

使用 androidx.lifecycle:lifecycle-runtime-compose

添加依赖:

1
implementation "androidx.lifecycle:lifecycle-runtime-compose:2.8.0"

然后使用:

LifecycleAware Composables

1
2
3
4
5
6
7
8
9
10
11
12
val lifecycleOwner = LocalLifecycleOwner.current
val lifecycleState by lifecycleOwner.lifecycle.currentStateAsState()
when (lifecycleState) {
Lifecycle.State.RESUMED -> { /* 处理 resumed 状态 */
}

Lifecycle.State.STARTED -> { /* ... */
}

else -> { /* ... */
}
}

或者直接监听事件:

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
@Composable
fun OnLifecycleEvent(onEvent: (owner: LifecycleOwner, event: Lifecycle.Event) -> Unit) {
val eventHandler by rememberUpdatedState(onEvent)
val lifecycleOwner = LocalLifecycleOwner.current

DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { owner, event ->
eventHandler(owner, event)
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
}

// 使用
@Composable
fun HomeScreen() {
OnLifecycleEvent { _, event ->
when (event) {
Lifecycle.Event.ON_START -> { /* ... */ }
Lifecycle.Event.ON_STOP -> { /* ... */ }
else -> {}
}
}
}