gpt4 book ai didi

viewmodel - Jetpack Compose 在 ViewModel 中观察 mutableStateOf

转载 作者:行者123 更新时间:2023-12-05 08:21:56 27 4
gpt4 key购买 nike

我需要更新用户配置文件开关

  1. View 模型
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.切换行

@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 中观察一个 MutableState 你可以使用 snapshotFlows as

var greet: MutableState<Boolean> = mutableStateOf(user.pushSetting.greet)

init {
snapshotFlow { greet.value }
.onEach {
updateUser()
}
.launchIn(viewModelScope)
//...
}

Create a Flow from observable Snapshot state. (e.g. state holdersreturned by mutableStateOf.) snapshotFlow creates a Flow that runsblock when collected and emits the result, recording any snapshotstate that was accessed. While collection continues, if a new Snapshotis applied that changes state accessed by block, the flow will runblock again, re-recording the snapshot state that was accessed. If theresult of block is not equal to the previous result, the flow willemit that new result. (This behavior is similar to that ofFlow.distinctUntilChanged.) Collection will continue indefinitelyunless it is explicitly cancelled or limited by the use of other Flowoperators.

关于viewmodel - Jetpack Compose 在 ViewModel 中观察 mutableStateOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69230831/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com