Compose docs say “`You should *not* pass ViewModel...
# compose
a
Compose docs say “`You should not pass ViewModel instances down to other composables."` Is it really that bad to do it? In my case I have a DropdownMenu in my ListItem Composable with 5 onClicks that all have to call a different method in my ViewModel. The problem now is that this ListItem ist 5 nested composables away from the viewModel reference in my “ProfileScreen” composable. So I would have to pass those 5 onClick Lambdas 5 times until it gets to the parent Composable. Do I have to get friends with this approach or is it not even that bad to pass down the viewmodel?
f
So I would have to pass those 5 onClick Lambdas 5 times
Or structure your UI hierarchy differently. By more leveraging "Slot API pattern" you could reduce the amount of nesting. And is it really that bad? Well, that depends on your use case but generally yes, it is. By passing a view model to your component, you are coupling it with that specific VM. What if you would want to use this component in different place? Or you would maybe refactor your VM in future removing some of the methods. You would also have to refactor your UI that shouldn't even know about existence of some view model in a first place. Like everything in programming it's finally up to you but these lint rules exist for a reason.
l
can you point me to where this guidance is given?
f
I thought it was a lint 🤦‍♂️ Probably got confused by reading about lint rules at Twitter
l
i think the guidance is a bit overstated potentially. the viewmodel is never going to be considered stable and so passing it into a composable will make it impossible for that composable to skip during Recomposition. this is also true of other potentially mutable classes so isn't unique to view models. additionally, i think that a composable taking a viewmodel as a parameter will be harder to test or reuse elsewhere, so this can help you there too. that said, if you're feeling overwhelmed by all of this guidance, there's nothing fundamentally wrong with any of this and you can happily pass your viewmodel wherever you want and Compose will be happy if you want to play around and come back to these things later
👍🏼 1
💪 2
👍 5