Proper way to operate collections in StateFlow

▼魔方 西西 提交于 2021-01-05 08:56:39

问题


I'm creating MutableStateFlow like this:

val intSet = MutableStateFlow(HashSet<Int>())

And in some moment later I want to update collection in this flow:

intSet.value.add(0)

And this doesn't seem to work (the collection updates, but observers are not notified). The way that I found it working:

val list = HashSet<Int>(intSet.value)
list.add(0)
intSet.value = list

But it creates copy of the collection, so it doesn't look proper for me. Is there any simpler way to update collection in StateFlow?


回答1:


MutableFlow does not check for changes in the content of collections. Only when the collection reference has changed it will emit the change.

Use immutable Set and use the += operator to add new elements. This will basically, create new Set and will trigger the change.

val intSetFlow = MutableStateFlow(setOf<Int>())
intSetFlow.value += 0


来源:https://stackoverflow.com/questions/65442588/proper-way-to-operate-collections-in-stateflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!