Hi all , is it a good practice to pass a viewmodel...
# compose
n
Hi all , is it a good practice to pass a viewmodel to a Composable function or referring a viewmodel inside a Compossable function
c
In general, no, you should try to avoid directly coupling your UI to a ViewModel. In practice, the VM must live somewhere within the Composition, but in that case it’s generally considered best practice to have 1 function which is the “stateless” version that accepts parameters of the relevant VM state properties and its callbacks, and a “stateful” version with accepts the ViewModel, collects the States from it, and forwards all that data into the “stateless” one. See this codelab for an example of this pattern. It uses the
GameScreen()
composable to pass in the VM, which does little more than connect the VM to the stateless
GameLayout()
.
❤️ 1
n
Thanks mate, I also agree but what I found when the VM got more state then the Composable need to have so many arguments for both state and the callback to modify the state, So is there a better way to do it
c
When the number of paramters/callbacks increases, it can be helpful to restructure your state to group it into “stateHolder classes”. This article goes into a lot of detail about stateholders, but it approaches the topic more from a perspective of how the core Material libraries use them to hide implementation details from the exposed API. It’s recommendations can make things a bit clunky and the logic difficult to follow for your main UI screen states. For building your own screen UIs, I find the MVI pattern to be the best way to adopt the “stateholder pattern” in a way that is both clean and easy to understand, yet also robust enough to handle anything you’d need. I maintain the Ballast MVI library as an opinionated take on MVI, which you may be interested in.
❤️ 1