https://kotlinlang.org logo
#compose
Title
# compose
k

Kyant

07/29/2022, 11:19 AM
Is there a way to observe the state of
MutableState
in the
init
function of
ViewModel
?
m

MR3Y

07/29/2022, 11:27 AM
snapshotFlow{ }
?
k

Kyant

07/29/2022, 12:08 PM
It works, thanks 👍. But why can't we use the compose feature directly in the VM?
m

MR3Y

07/29/2022, 12:44 PM
You mean like you can't use
MutableState
directly in VM?
k

Kyant

07/29/2022, 12:48 PM
Not exactly. I think the way to observe the MutableState in VM is somehow complex.
m

MR3Y

07/29/2022, 1:02 PM
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

Adam Powell

07/29/2022, 1:14 PM
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

Kyant

07/29/2022, 1:16 PM
I want to automatically fetch some data when the state changes.
c

Colton Idle

07/29/2022, 1:44 PM
snapshotFlow{}! TIL Thanks @MR3Y
320 Views