Just curious: what happens if youre emitting a cla...
# coroutines
z
Just curious: what happens if youre emitting a class with mutable properties to a
StateFlow
? Id think that the first emission comes through, but if you then edit the class and emit it anew, nothing will come through given how StateFlow compares equals before emitting new items?
a
StateFlow
just calls
equals()
to compare the values, and an object always equals itself (unless you override the method and return false, which is wrong anyway).
z
I understand, but what if you were to use a data class with a mutable property? Im just referring to the logic where the item inside the StateFlow.value is actually mutated, which is what I think would happen if you were to emit Item below, then do item.label = "xyz" and emit it again? Of course, I would never do that - but Im still interested in learning what would happen (Im not at my computer to test this 😅).
Copy code
data class Item(
    var label: String
)
a
Since you are emitting the same object, it will equal itself. Whether you have changed the value is irrelevant.
You can think like this: the
item
variable and the value in the state flow is the same object, so when you change
item.label
from outside, the
label
of the object inside the state flow is also changed.
z
Exactly my thinking, thanks for confirming!
t
@Albert Chang you sure about that? Data Classes override equals by default, so the inner values are relevant for the equallity. If one changes the
label
inside the
Item
object, the equals check should see unequal objects.
a
@Timo Gruen Think of this example:
Copy code
val item1 = Item(label = "1")
val item2 = item1
item2.label = "2"
println(item1 == item2)
What will it print? You can also run it yourself.
t
Yeah my bad, im busted. Have been working with immutabillity for the past 4 years and basically forgot on how references work
p
What happens is you’ll probably regret it later 😃 Using mutable data in streams is a recipe for headache