Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to operate collections in StateFlow

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?

like image 930
Kiryl Tkach Avatar asked Oct 21 '25 14:10

Kiryl Tkach


1 Answers

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
like image 143
Nikola Despotoski Avatar answered Oct 23 '25 06:10

Nikola Despotoski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!