本文介绍了Jetpack组合在视图模型中观察muableStateOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要更新用户配置文件开关
- 视图模型
class ProfileViewModel : BaseViewModel() {
var greet = mutableStateOf(user.pushSetting.greet)
var message = mutableStateOf(user.pushSetting.message)
var messageDetails = mutableStateOf(user.pushSetting.messageDetails)
var follow = mutableStateOf(user.pushSetting)
var like = mutableStateOf(user.pushSetting.like)
var comment = mutableStateOf(user.pushSetting.comment)
fun updateUser() {
println("--")
}
}
2.可组合
@Composable
fun SettingCard(viewModel: ProfileViewModel) {
Lists {
Section {
TextRow(text = "手机号码") { }
TextRow(text = "修改密码", line = false) { }
}
Section {
SwitchRow(text = "新好友通知", checkedState = viewModel.greet)
SwitchRow(text = "新消息通知", checkedState = viewModel.message)
SwitchRow(text = "消息显示详细", line = false, checkedState = viewModel.messageDetails)
}
}
}
3.SwitchRow
@Composable
fun SwitchRow(text: String, line: Boolean = true, checkedState: MutableState<Boolean>) {
ListItem(
text = { Text(text) },
trailing = {
Switch(
checked = checkedState.value,
onCheckedChange = { checkedState.value = it },
colors = SwitchDefaults.colors(checkedThumbColor = MaterialTheme.colors.primary)
)
}
)
}
如何观察开关的变化并在ViewModel中调用updateUser()
我知道这是一种方法,但它并不理想。网络更新将在每次初始化时被调用。有没有更好的解决方案?
LaunchedEffect(viewModel.greet) {
viewModel.updateUser()
}
推荐答案
此问题的最佳解决方案是将unidirectional flow与SwitchRow
一起使用,@Codecameo建议使用lambda。
但如果要观察Viewmodel
中的MuableState,则可以使用snapshotFlow
%s作为
var greet: MutableState<Boolean> = mutableStateOf(user.pushSetting.greet)
init {
snapshotFlow { greet.value }
.onEach {
updateUser()
}
.launchIn(viewModelScope)
//...
}
这篇关于Jetpack组合在视图模型中观察muableStateOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!