问题
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