How do you observe a mutable object that fires eve...
# compose
r
How do you observe a mutable object that fires events when it changes? Code that doesn't work...
Copy code
@Composable fun Things(model: MyViewModel) {
    val mutableThing = model.thing
    mutableThing.addChangeListener { recomposeThisStuff() }  
    Text("${mutableThing.size} ...")
So "model.thing" may always be the same reference/object. But it changes internally.
Or is Compose meant to be used mainly with immutable types? I like Kotlin's immutable/persistent collections, but sometimes it's harder, when dealing with more complex types, to make everything immutable. Not sure if I should be trying to do that or not.
l
Convert
thing
to a
MutableState
in your ViewModel, and just do
Text("${model.thing.size}")
r
But the value
model.thing
never changes. As far as Compose is concerned, that mutable state is not changing. Am I supposed to observe the object and then call
thing.value = thing.value
to try and trigger a recompose?
Note that in that linked article, all the MutableStates contain immutable types, like String.
l
In your view model, you have to change the value of your mutable state in order to trigger a recomposition
Try creating a function in your view model that updates the current value and see how the value changes in your UI
If your value is never updated, you might be missing a "remember" call somewhere. Make sure that your view model instance is always the same
r
Here's some code to illustrate my question: https://pastebin.com/aTvs1i9w
The "Thing" is a mutable object with its own way of notifying observers of changes. It seems like this doesn't fit well with Compose's MutableState. With a mutable object, there is only one instance, so you can't "change the value" of the MutableState.
Ah... I discovered the 2nd arg to
mutableStateOf()
. So this one line change makes my example work.
var thing1: Thing by mutableStateOf(Thing(), neverEqualPolicy())
. Seems odd though, so I still wonder if there is a better way.
a
Given the rest of your setup and assuming you can't change
Thing
, using
neverEqualPolicy
is fine there
r
What if I could change
Thing
? Should I try to make it completely immutable, or is there another way to make mutable objects that works better with Compose?