When working in the ViewModel with Compose, which ...
# compose
p
When working in the ViewModel with Compose, which is the difference between working with
var myVar by _mutableStateOf_("")
and
var myVar = _MutableStateFlow_("")
and why should I choose one? In theory as I can see both works for observe changes in the state of the application managing those variables in the ViewModel and generate recompositions, but working with
by mutableStateOf
is way more simple, light and easy than working with
MutableStateFlow
but everywhere I can see samples with
MutableStateFlow
and not
by mutableStateOf
. What I'm losing?
a
https://developer.android.com/topic/architecture/ui-layer/state-production has examples of each and has more info on when you might choose one over the other. You are absolutely right that both
MutableStateFlow
and
mutableStateOf
each provide a observable, mutable container of state. The main difference is the system in which they operate, which influences how you can interact and combine them -
MutableStateFlow
operates with the
Flow
APIs, and
mutableStateOf
operates in Compose's snapshot state system. The two systems are distinct, but there are also tools to cross between them - like
snapshotFlow
(Compose snapshot state ->
Flow
) and
collectAsState
/
collectAsStateWithLifecycle
(
Flow
-> Compose snapshot state)
> but working with
by mutableStateOf
is way more simple, light and easy than working with
MutableStateFlow
If that is what you're finding, then by all means you can prefer to use that. If your
ViewModel
is only being used to drive Compose UI, there's no technical reason why you have to use just one or the other. I also personally prefer to stay in the Compose state system as much as I can.
p
great answer, thank you, maybe can you tell me a simple example of a situation in which
MutableStateFlow
become necessary over
mutableStateOf
to reach the functionality?
c
As said, it’s not about functionality. By using
mutableStateOf
you make your view model depend on the compose library. So if you want to have a more independent view model you should rather use the flow.
p
I understand, thanks
s
Funnily enough, if you want to have a more generic ViewModel, compose won't even likely be your issue, since that's perfectly multiplatform, it'd be the ViewModel class itself which isn't yet 😅 I feel like fear for "making it more generic" really isn't a real concern for almost everybody, so feel free to just do it if it works for you.