Anyone achieved to inject a ViewModel on a compose Preview? Does it even make sense? What's the best approach to be able to preview a screen?
a
Abhishek Dewan
05/22/2021, 4:43 PM
You can inject a viewModel by giving the viewModel param a default value in the composable function and using the get() call from Koin
As for the preview I've found breaking your composable into two parts. one that holds your view and one that manages state. for eg. If you were writing a composable that shows a list. you could potentially write a ListScreen composable that accepts a viewModel and then renders a ListScreenContent composable with all of the data passed as params into it. This way you can preview the ListScreenContent composable by providing whatever values it needs to render itself
an example of it is here https://github.com/abhishekdewan101/Scout/blob/0522ed3a846c45dc5e49155b53254ce4bdd4efc4/app/src/main/java/com/abhishek101/gamescout/features/onboarding/splash/SplashScreen.kt#L26
n
Nacho Ruiz Martin
05/22/2021, 5:55 PM
What you stated about separating the main composable from the content itself makes a lot of sense.
Thanks for the tip, I’ll go in that direction. And thanks for sharing your code.