jetpack compose 是模仿 react 的方式写 UI。用了一段时间下来,感觉 compose 有个不错的改进,即缓存与可观测分开为两步。
@Composable
fun App(myViewModel: MyViewModel) {
val openLoginDialog = remember { mutableStateOf(false) }
//...
}
其中 remember 构建缓存,而 mutableStateOf() 构建可观测状态。
如果可观测状态 state放在外面的 view model 中,则不需要做 remember 的缓存,因为 view model 不会像视图那样刷新。使用时直接引用 view model 中的可观测状态即可。
@Composable
fun App(myViewModel: MyViewModel) {
Column() {
Text(
text = "${myViewModel.myNum.value}",
fontWeight = FontWeight.Bold,
fontSize = 20.sp,
modifier = Modifier.padding(8.dp)
)
Button(onClick = { myViewModel.increaseNum() }) {
Text(text = "increase")
}
}
}
class MyViewModel: ViewModel() {