例如,我将数据加载到列表中,它由 MutableStateFlow 包装,然后将它们收集为 UI 组件中的状态。
问题是,当我更改 MutableStateFlow 中的某个项目(例如修改属性)但不添加或删除时,UI 不会更改。
那么,当我修改 MutableStateFlow 的某个项目时,如何更改 UI?
这些是代码:
视图模型:
data class TestBean(val id: Int, var name: String)
class VM: ViewModel() {
val testList = MutableStateFlow<List<TestBean>>(emptyList())
fun createTestData() {
val result = mutableListOf<TestBean>()
(0 .. 10).forEach {
result.add(TestBean(it, it.toString()))
}
testList.value = result
}
fun changeTestData(index: Int) {
// first way to change data
testList.value[index].name = System.currentTimeMillis().toString()
// second way to change data
val p = testList.value[index]
p.name = System.currentTimeMillis().toString()
val tmplist = testList.value.toMutableList()
tmplist[index].name = p.name
testList.update { tmplist }
}
}
UI:
setContent {
LaunchedEffect(key1 = Unit) {
vm.createTestData()
}
Column {
vm.testList.collectAsState().value.forEachIndexed { index, it ->
Text(text = it.name, modifier = Modifier.padding(16.dp).clickable {
vm.changeTestData(index)
Log.d("TAG", "click: ${index}")
})
}
}
}
Both Flow
Compose 可变状态无法跟踪包含对象内部所做的更改。
但您可以用更新的对象替换对象。data class
是一个很好用的工具,它将为您提供一切copy
开箱即用,但你应该使用var
并且只使用val
为您的领域避免错误。
查看为什么不变性在函数式编程中很重要? https://www.quora.com/Why-is-immutability-important-in-functional-programming
testList.value[index] = testList.value[index].copy(name = System.currentTimeMillis().toString())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)