https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

Zoltan Demant

03/09/2023, 6:10 AM
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

Albert Chang

03/09/2023, 6:34 AM
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

Zoltan Demant

03/09/2023, 6:54 AM
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

Albert Chang

03/09/2023, 6:56 AM
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

Zoltan Demant

03/09/2023, 7:01 AM
Exactly my thinking, thanks for confirming!
t

Timo Gruen

03/09/2023, 7:50 AM
@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

Albert Chang

03/09/2023, 8:09 AM
@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

Timo Gruen

03/09/2023, 8:22 AM
Yeah my bad, im busted. Have been working with immutabillity for the past 4 years and basically forgot on how references work
p

Patrick Steiger

03/10/2023, 8:46 PM
What happens is you’ll probably regret it later 😃 Using mutable data in streams is a recipe for headache
3 Views