Chachako
03/22/2021, 2:59 PMState
in ViewModel
is much simpler than LiveData
. Should I use MutableState
in ViewModel
? Is this correct?Albert Chang
03/22/2021, 3:35 PMOlivier Patry
03/22/2021, 3:38 PMOlivier Patry
03/22/2021, 3:38 PMFlow
on ViewModel and collectAsState
on Compose sideOlivier Patry
03/22/2021, 3:39 PMLiveData
within VM to allow reusing ViewModel
in Desktop Compose)BenjO
03/22/2021, 6:20 PMFlow
(or even`StateFlow` to avoid setting default values in when calling collectAsState
) from ViewModel's makes them only Kotlin dependent, not Android. This is an architectural choice, it depends on the boundaries and where you want to set them.Nathan Castlehow
03/23/2021, 1:17 AMAlbert Chang
03/23/2021, 3:17 AMState
as the LiveData
for compose. If your project is pure compose, there's no reason to use LiveData
.Chachako
03/23/2021, 3:22 AMMutableState
in the ViewModel
in compose-samples.Albert Chang
03/23/2021, 3:24 AMZach Klippenstein (he/him) [MOD]
03/23/2021, 3:27 AMSean McQuillan [G]
03/23/2021, 8:50 PMState<T>
vs any async type. Then any writes during event handlers (e.g. onClick) will be correctly applied in-sync with the next composition, and other side effects that will generally make things more efficient / feel more performant.
If you're adding State that is naturally async (e.g. reading from a network, database), then there is no compelling reason to use State<T>
over Flow
and whatever is the most natural would be the right choice.
The big caveat about using State<T>
is that it's not designed to be a stream of any kind or consumed outside of Compose, and is not a replacement for Flow<T>
. If you intend to use it as a stream, Flow
is a better choice.Sean McQuillan [G]
03/23/2021, 8:50 PMState<T>
in a ViewModel as long as it's intended for use by Compose. In some situations State<T>
will offer more consistent and efficient behavior than other options when used in Compose.Sean McQuillan [G]
03/23/2021, 8:55 PMZach Klippenstein (he/him) [MOD]
03/23/2021, 10:07 PMState
and Flow
that is kind of related to what you’re talking about I think.Sean McQuillan [G]
03/23/2021, 11:53 PMState<T>
writes are always applied in the next composition after they're committed consistently and changes are batched together (so if you change 5 states before the next batch is applied, only one recomposition is triggered)Sean McQuillan [G]
03/23/2021, 11:55 PMSean McQuillan [G]
03/23/2021, 11:57 PMState<T>
at the high level as a pending changes posted to a composition applier; when the batch is applied all pending changes are processed together and applied at once in a single recomposition. You don't have to do anything to wire this up between the various states, it's baked into how State<T>
and compose interact.Sean McQuillan [G]
03/23/2021, 11:58 PM