Hi, I have some properties on my view model which my view subscribes to. One of these is created by ...
n
Hi, I have some properties on my view model which my view subscribes to. One of these is created by “derivedStateOf”. I am trying to keep my view light so when this derived state changes i need to do a bunch of steps inside in a function in my view modell. Is there any way to subscribe to “derivedStateOf” inside a view model (ie outside of the composable) or do i need to instead make these properties a flow so i can subscribe to them both inside and outside of a composable? Thanks!
a
Can you share some.more specifics about the use case? There are several potential ways to approach this.
n
@Adam Powell so I have a MutableState value which gives me the current position of a video which is playing. From there my derived state looks up some info based on that value (in this case the section of the video which is currently playing). When the derived value changes i need write some bluetooth data. I want to avoid putting this in the view and keep it all in the view model hence thinking i might need to shift to flows.
Sorry if the specific implementation details complicates it but basically reacting to derived state to perform side effects all within a view model in order to keep the view light.
a
I see.
snapshotFlow {}
might help you then
when collected, it will emit the current value of the expression, and it will re-evaluate and emit the new value whenever any snapshot inputs of the expression change
n
@Adam Powell Thanks! That seems to work pretty well. When we have a view model interacting with compose do we want to favour using State or am I just overcomplicating it by using derived state to start with and it should just be some sort of flow to start with?
a
Without seeing the code it's hard to judge, but I'd expect that no, it's not overcomplicating it. There might be a call to make between using derivedStateOf or simply computing the needed data on the fly from snapshot state in a function; the difference there is usually in whether you want to cache the result between input changes, it's observable either way.
Compose's collectAsState extensions all create mutableStateOf holders for the latest values anyway, it's not like you would get rid of translation layers if you need the data in both forms in different places, you're just choosing where to put the translation.
n
Makes sense. Thanks for all your help on this one! 🙂
👍 1