Pablo
02/23/2024, 5:12 PMvar 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?Alex Vanyo
02/23/2024, 5:36 PMMutableStateFlow
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)Alex Vanyo
02/23/2024, 5:36 PMby 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.Pablo
02/23/2024, 5:44 PMMutableStateFlow
become necessary over mutableStateOf
to reach the functionality?Chrimaeon
02/23/2024, 5:46 PMmutableStateOf
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.Pablo
02/23/2024, 5:51 PMStylianos Gakis
02/23/2024, 7:51 PM