Updating a single item's quantity in a `MutableSta...
# coroutines
c
Updating a single item's quantity in a
MutableStateFlow<List<Item>>
does not trigger flow emission. Add / remove of an item triggers an emission. I'm listening to this flow (cartItems) with a
transform
which is never triggered when I modify the quantity of a product within the list. But the value does change in the list (Can confirm because if I click
+
n times and then
-
n times recomposition happens. Question How should I update an item
MutableStateFlow<List<Item>>
such that
emission
is triggered and
transform
is triggered?
s
StateFlow does a equals to conflate values. If the list has the same reference it will not emit it. You will have to create a new list every time you add or remove items in it.
👍🏻 1
c
Oh so when I update an individual item's property the data is changed but the flow is not emitted because the memory reference is the same. Am I right?
s
Yup. A call to emit will do an equality comparison first (== or .equals()) and if the newly emitted item is equal, no emission will take place. In general, reeeeeaaaaally try to avoid emitting mutable objects. This will introduce subtle, hard to debug issues, even if you did implement the .equals() operator correctly. Emit only immutable objects.
m
And as for immutable collections, this might help: https://github.com/ansman/kotlinx.collections.immutable
z
Idk what that fork is for but if you want to use that library you probably want to use the official one: https://github.com/Kotlin/kotlinx.collections.immutable
👍 1