https://kotlinlang.org logo
#compose
Title
# compose
p

Pablo

02/26/2024, 7:04 PM
When you have a Compose App with 4 screens but only a ViewModel (it's an official sample project, not mine), should all four screens receive the ViewModel as a parameter of their composable or should the ViewModel be only accessed on the main screen that haves the navController and do all the calls to the ViewModel in the lambda functions passed as parameters to the screens? The first option seems more simple, but I'm not sure that if it is a good practice to pass the ViewModel to the screens of the app.
s

Sean Proctor

02/26/2024, 7:18 PM
I would be thinking more about why you're doing everything in a single ViewModel. The docs suggest only passing a ViewModel to the screen Composable, but whatever makes more sense in your project. Unless you have 4 views on the same data/functions, I would suggest breaking up your ViewModel into the components used on each screen.
s

Stylianos Gakis

02/26/2024, 10:19 PM
Please if you value your future self's time, split the ViewModels before it's too late 😅
With that said, on a nav destination, when you try to get a ViewModel (by ViewModels, or hiltViewmodel or koinViewModel) you can pass a lifecycle owner. If you want a VM scoped to your entire activity instead of to your current destination, you can do exactly that, pass the activity as the owner.
p

Pablo

02/27/2024, 8:38 AM
thank you guys, It's an official sample project from a google codelab, I know that each screen should have it's own viewmodel.
please, if can someone answer my question, I still didn't know the answer
p

Pablo

02/27/2024, 10:11 AM
please read carefully my question, that doesn't answer my question
s

Stylianos Gakis

02/27/2024, 10:12 AM
Access the ViewModel inside your destinations by providing the activity as the lifecycle owner viewModelStoreOwner (actually I think it's called that). That will make your VM be scoped to the activity, therefore be global, therefore be shared amongst your four destinations. That is my answer to your original question.
Or better yet, leave the activity out of this, scope it to the root route of your NavGraph, you are using androidx.navigation right?