Ryan Smith
10/27/2022, 12:52 AMFlow
and Compose
? One of the predominant lessons I've been learning is "make your composables stateless by hoisting". I'm trying to adhere to this by exposing as much state as makes sense through properties on my view models.
For example, my data layer has an in-memory Repository that exposes a collection of items through a Flow
. My view model is meant to collect
that flow as state, and expose that state to my Table
composable to be displayed on the screen. But since collectAsState
is marked as @Composable
I can't call it from my view model. As I see it I could either pass the Flow
directly through my view model to my Table
composable or stick with mutableStateOf
and collect the Flow
internally to the view model and just expose the MutableState
to my Table
.
More generally, though, it feels like the two ideas "state through the view model" and "collectAsState is Composable-only" are at odds here, which makes me think there's "the way" to do this sort of thing that I'm not seeing right now.Casey Brooks
10/27/2022, 12:59 AMcollectAsState()
is done to connect the reactive Flow
into the UI/Compose world. ViewModels, by nature, live above the UI, and so should not be using State<T>
, but instead still working with Flow
.
So what you’d want to do is have your ViewModel process your Repository’s Flow in some manner, and then expose its own Flow (or StateFlow) which contains the data from the Repository and also the other stuff you’re managing in your ViewModel. And then your Compose code calls collectAsState()
on your ViewModel’s Flow, and is completely ignorant of the RepositoryRyan Smith
10/27/2022, 1:15 AMcollectAsState
to be a convenient way to achieve the last part. Instead it sounds calling collect on a Flow from the UI is not only okay it's a good way to bridge the two worlds. Is that right?Kirill Grouchnikov
10/27/2022, 1:52 AMRyan Smith
10/27/2022, 2:01 AM