然后我们分析下这个例子只有一个count 状态和add 操作,因此这样来实现viewModel,这里基于jetpack viewmodel和livedata组件来实现
class MvvmViewModel : ViewModel() {
val countState = MutableLiveData(1)
fun add(num: Int) {
countState.postValue(countState.value as Int + num)
}
fun reduce(num: Int) {
countState.postValue(countState.value as Int - num)
}
}
接下来我们就需要实现Screen,在Screen中将Content和ViewModel结合起来
@Composable
fun Screen1(
navController: NavController
) {
val viewModel: MvvmViewModel = viewModel()
val count by viewModel.countState.observeAsState(0)
Content1(count = count,
{ navController.navigate(“screen2”) }
) {
viewModel.add(1)
}
}
我们可以看到借助于viewModel()方法我们可以在jetpack compose中很方便快捷的创建viewModel,同时也可以将livedata方便的转换为compose state,当state发生变化时,界面就会自动重组并显示&#x