gpt4 book ai didi

Android LiveData/StateFlow 列表项属性更新问题

转载 作者:行者123 更新时间:2023-12-04 23:50:21 29 4
gpt4 key购买 nike

所以我正在更新我的RecylerViewStateFlow<List>如下所示:
我的数据类:

data class Student(val name: String, var isSelected: Boolean)
我的 ViewModel 逻辑:
fun updateStudentsOnSelectionChanged(targetStudent: Student) {
val targetIndex = _students.value.indexOf(targetStudent)
val isSelected = !targetStudent.isSelected

_students.value[targetIndex].isSelected = isSelected //<- doesn't work
}
问题: UI 没有改变,但 isSelected里面 _student变了,怎么回事? (与 LiveData 相同)

最佳答案

我假设 _studentsStateFlow<List> .更改 isSelected Student 的属性(property)模型不会触发 StateFlow .解决方法是使 isSelected Student 的属性(property)数据类不可变以在设置新状态时对其进行比较,创建 MutableList退出当前列表并复制现有的Student具有 isSelected 新值的对象属性(property):

data class Student(val name: String, val isSelected: Boolean)

val students = _students.value.toMutableList()
students[targetIndex] = students[targetIndex].copy(isSelected = isSelected)
_students.value = students

关于Android LiveData/StateFlow 列表项属性更新问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71187022/

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