https://kotlinlang.org logo
e

escodro

03/02/2021, 5:21 PM
Hello, everyone! I’m having some issues with ViewModel + Hilt + Navigation. I already took a look at previous discussions but I need some advice. I have a
Home
screen that contains 4 tabs, each one with its own
ViewModel
. Today it is declared this way:
Copy code
composable(Destinations.Home) {
    Home(
        onTaskClicked = actions.openTaskDetail,
        onAboutClicked = actions.openAbout
    )
}
But since calling
viewModel()
to get the ViewModels for each Composable does not work, how should I proceed? Get the 4 ViewModels inside my
NavGraph
and pass then all to my
Home
? Should I create a
HomeViewModelProvider
containing the 4 ViewModels? Is there a better approach? Thanks a lot in advance! ❤️
i

Ian Lake

03/02/2021, 5:32 PM
You can certainly pass in the
ViewModelProvider.Factory
you get from
HiltViewModelFactory(AmbientContext.current, it)
- as long as you use that Factory with
viewModel()
, it will work just fine
🎉 1
e

escodro

03/02/2021, 5:46 PM
Thanks a lot, Ian. It worked! 😊 Is it okay to pass the
ViewModelProvider.Factory
around or we will get some alternative in the future?
i

Ian Lake

03/02/2021, 5:56 PM
As per that previous discussion you linked, you'll need to pass a Factory or use the upcoming
hiltNavGraphViewModel()
👍 1
c

Colton Idle

03/02/2021, 10:13 PM
Migrated to hilt beta yesterday and hiltNavGraphViewModel works like a charm. Big thanks to everyone who got that working.