https://kotlinlang.org logo
j

Jason Ankers

01/25/2021, 7:19 AM
Is it possible to scope a viewmodel to a navigation graph with navigation-compose?
1
f

fmasa

01/25/2021, 9:20 AM
AmbientViewModelStoreOwner
is scoped to NavBackEntry by default. But you can pass "parent"
AmbientViewModelStoreOwner
(the ambient value passed to given
NavHost
) as your own ambient.
I pass Activity that way (using custom
AmbientActivity
) to scope few viewmodels that are used everywhere to Activity
j

Jason Ankers

01/25/2021, 9:36 AM
Ok cool, so I think thats working. I’m using Hilt to inject some dependencies into my ViewModel, which fails now because I’m creating the ViewModel with a ViewModelProvider. I think I need to pass a ViewModelProvider.Factory but I’m not sure where to get it in compose. Previously in fragments I was using
defaultViewModelProviderFactory
, do you know if theres a substitute in compose? Before compose I had this: https://developer.android.com/training/dependency-injection/hilt-jetpack#viewmodel-navigation
f

fmasa

01/25/2021, 9:40 AM
Don't know about that. I use Koin right now 😕
👍 1
f

FunkyMuse

01/25/2021, 11:09 AM
If you're using navigation compose by default they're scoped to the navigation graph
f

fmasa

01/25/2021, 11:14 AM
but only view models accessed via
navGraphViewModels
, right?
AmbientViewModelStoreOwner
(used by
viewModel()
) is
NavBackStackEntry
.
i

Ian Lake

01/25/2021, 3:11 PM
This Wednesday will be a good day for you - new APIs in Navigation Compose are coming out to get the
NavBackStackEntry
of parent graphs as well as a new Hilt Navigation artifact which gives you access to a properly scoped Hilt
ViewModelProvider.Factory
👍 10
j

Jason Ankers

01/25/2021, 4:08 PM
@Ian Lake Great news 😄
33 Views