Marcello Galhardo
10/29/2021, 5:40 PMMutableState
and State
inside a ViewModel
? For example, why would someone choose a MutableStateFlow
in a ViewModel
and do a collectAsState
instead of simple using a MutableState
at first place? 🤔Brian G
10/29/2021, 5:44 PMState
is fine to use, unless you are writing multiplatform code. State
requires the Compose dependency, while Flow
does not.Marcello Galhardo
10/29/2021, 5:48 PMeygraber
10/29/2021, 7:40 PMState
is common code, so it could be used in a multiplatform project.
One reason to use MutableStateFlow
/ collectAsState
would be to keep your state entirely immutable (i.e. if state changes a whole new object is emitted vs updating your existing state). This is helpful in architectures like MVI.Brian G
10/29/2021, 9:32 PMState
is in androidx.compose.runtime
, I don't think that's published for iOS (yet)Marcello Galhardo
10/29/2021, 10:54 PMeygraber
10/30/2021, 11:56 PMFlow
works, except it's more hidden because you're doing it through state emissions (also the distinction blurs depending on how you work with it, i.e. MutableStateFlow.value
vs doing everything with a flow API).Marcello Galhardo
10/31/2021, 10:23 AMMutableState
, you would still change it by using MutableState.value = newValue
- which from my understanding is exactly what you described above with StateFlow
.
Reference: https://developer.android.com/reference/kotlin/androidx/compose/runtime/MutableState
Honest question: what is more hidden? Isn't the state emissions exactly the same? 🤔eygraber
10/31/2021, 3:26 PMFlow
for collectAsState
then you're not setting value
anywhere; you're just emitting your state. If you use MutableStateFlow
then it is much closer to how MutableState
works.
I think using MutableState
in this way "sort of" defeats its advantage over collectAsState
. The way I'm using it to have a MutableState
for each field so that I can limit the recomposition to the specific scope where that discrete read is.
By having your whole state in a MutableState
that you read in a top level composable, recomposition will affect that whole subtree.Marcello Galhardo
11/02/2021, 8:25 AM