It is advised not to pass viewmodel objects down t...
# compose
v
It is advised not to pass viewmodel objects down to child composables, is this due to increased coupling and worse testability or are there some other reasons too? Context: Some of my screens mostly consist of "sub-screens" that definitely don't need to be reusable, would it be bad practice to just directly pass the viewmodel down a few layers of parent layout composables?
c
you also loose the ability to create preview-s for your subscreens
your subscreens will share a huge state, with things the particular subscreen should not even know about. eg. fields used in Subscreen1 will be available for Subscreen2
v
Thank you for the response, I'll create separate state holders for the sub-screens
đź‘Ť 2
Just as a curiosity though, what would be the practical consequences of having the subscreens share some state?
c
There is no direct consequence I guess, you could get away with it just fine. But you have to be really careful how you implement things. You introduce much more complexity than needed. You give room for mistakes that otherwise could not even exist.
🙏 1
Handling and triggering Recompositions might also be trickier, harder to reason about. You mentioned worse testability, I mentioned not being able to have previews, and the only upside is it is easier to implement
🙏 1
So it is hard to tell if you will regret it, or it will work great. If you are sure a “few layers” wont end up being every layer, then it might work, but I would not risk it personally, just to cut a few corners
r
You haven’t really explained why you want to do this. If your goal is to have subscreens observe some subset of the state then you’re probably reimplementing some of what Compose already does which is likely to be a bad idea
If you just want to avoid some boilerplate of passing lots of callbacks so the subscreens can send events back to the VM I’d say that’s probably fine
(as already explained though this will make your subscreens harder to test and really doesn’t save much boilerplate)
v
I was actually kind of doing both before -- the subscreens only need a subset of the state and callbacks. What do you mean by "Compose already does this"?
Would the better pattern here be separate state holders for the subscreens like I was planning to refactor?
r
Only the top level should be observing for changes in state and then passing (subsets of) the required state to its children
children don’t need the VM for this because it’s driven by the parent
c
I basically do what the last answer in the above ^ thread says. BUT i have made exceptions in some cases where I have a "subscreen" inside of a screen. A good example is when I have a complex bottom sheet in my Screen, then I will just pass the VM, but after that point I don't pass it down any further.
105 Views