从存储在房间DB实体类中的列表中创建流或寿命
我有一个我存储在房间数据库中的课程。该类包含一个可变的列表,其中不时添加和删除元素。现在,我想观察UI中列表内容的更改,例如,我想在文本视图中显示数组的大小。以下是一个示例类。我该怎么做?
class MyClass(
@PrimaryKey var id: Long = 0L,
var myList: MutableList<Int> = mutableListOf()
) : Serializable {
fun addElement(value: Int) { myList.add(value) }
}
将mylist
更改为可观察的(livedata/stateflow)无法使用,因为列表本身保持不变,只有内容会更改。 如果列表已更改并更新值,我可以启动一个检查每个MS的Coroutine,但这是非常糟糕的代码。
我可以添加一个变量,该变量在列表更新时可以手动更新,例如
private val _arraySize: MutableStateFlow<Int> = MutableStateFlow(myList.size)
val arraySize: StateFlow<Int>
get() = _arraySize
fun addElement(value: Int) {
myList.add(value)
_arraySize.value = myList.size
}
,这会炸开类,我必须@ignore
所有流量,因此它们不会存储在DB中,尤其是在我不仅需要大小,还需要从数组计算得出的最大,最小值和其他值。
有更好的解决方法吗?
I have a class which I store in a room database. The class contains a mutable list where elements are added and removed from time to time. Now I want to observe the changes of the content of the list in the UI, for example I want to show the size of the array in a TextView. Below is an example class. How can I do this?
class MyClass(
@PrimaryKey var id: Long = 0L,
var myList: MutableList<Int> = mutableListOf()
) : Serializable {
fun addElement(value: Int) { myList.add(value) }
}
Changing myList
to an observable (LiveData/StateFlow) won't work, because the list itself remains the same and only the content changes.
I could start a coroutine that checks every n ms if the list has changed and update the value, but this would be very bad code.
I could add a variable that gets manually updated when the list gets updated, e.g.
private val _arraySize: MutableStateFlow<Int> = MutableStateFlow(myList.size)
val arraySize: StateFlow<Int>
get() = _arraySize
fun addElement(value: Int) {
myList.add(value)
_arraySize.value = myList.size
}
But this blows up the class and I have to @Ignore
all the Flows so they do not get stored in the DB, especially if I want e.g. not only size but also maximum, minimum, and other values calculated from the array.
Is there a better way to solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论