Could anyone try to help me understand something w...
# compose-desktop
r
Could anyone try to help me understand something with
Flow
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.
c
Generally-speaking,
collectAsState()
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 Repository
r
It makes sense that the UI should be completely ignorant of the Repository. I was trying to achieve that by having the view model operate on the Flow from my Repository as you suggested, but then ultimately collect it as well and then expose that result to the UI through some State. I believed
collectAsState
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?
k
These general questions are better posted in #compose that has a bit wider audience and a bit more exposure
r
That's a fair point, I can x-post there as well. I initially decided not to to avoid the discussion ending up on Android-specific constructs like ViewModel or LiveData as solutions.