Is there a way to observe the state of `MutableSta...
# compose
k
Is there a way to observe the state of
MutableState
in the
init
function of
ViewModel
?
m
snapshotFlow{ }
?
k
It works, thanks 👍. But why can't we use the compose feature directly in the VM?
m
You mean like you can't use
MutableState
directly in VM?
k
Not exactly. I think the way to observe the MutableState in VM is somehow complex.
m
it is more complex than observing state in a
@Composable
function because being in a composable context gives you additional benefits automatically like invalidating composition, layout or drawing when state changes because Compose is monitoring snapshot reads for you under the hood. this is not the case in the VM, it doesn't know how to monitor & observe those snapshot reads for you. So, you are using some utilities like
snapshotFlow{}
to workaround that.
the same applies to writing to states as well, in a VM, you would use something like
Snapshot.withMutableSnapshot
to ensure you're updating state in an isolated thread-safe way before trying to apply this change to be available to other threads. In a
@Composable
you're not doing that, just make sure to Avoid backwards writes
a
What is it that you're trying to observe in the ViewModel? Does the ViewModel need to observe snapshot state changes or is it sufficient to use snapshot state in calculations it makes, and rely on callers observing those reads implicitly?
k
I want to automatically fetch some data when the state changes.
c
snapshotFlow{}! TIL Thanks @MR3Y
457 Views