Hey guys, I have a question about how to obtain a ...
# compose
l
Hey guys, I have a question about how to obtain a
ViewModel
properly. dev14 added a
viewModel()
composable: Let’s say we need a
ViewModel
instance in multiple composable functions. Should we explicit obtain the instance via
viewModel()
in every composable function or should we obtain it once on top of the compose hierarchy and then pass it the way down?
s
Answer to your question, prefer to take it once and pass it. Longer answer, prefer to code so that multiple composables don't depend on a concrete ViewModel. In code I've seen this is often done to allow children composables to pass events. A ViewModel is an inherently stateful object that tends to have a large API so it's better to limit it to one composable if possible. Then pass values and onEvent* lambdas to child composables. This isn't always the best coding style but it's a good default starting point.
👆 1
👍 1
Following this pattern of limiting stateful objects to a single composable makes the rest of your code stateless / simpler / easier to test
👆 1
👍 1
l
Thanks that helped me!