Is it possible to scope a viewmodel to a navigatio...
# compose
j
Is it possible to scope a viewmodel to a navigation graph with navigation-compose?
1
f
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
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
Don't know about that. I use Koin right now 😕
👍 1
f
If you're using navigation compose by default they're scoped to the navigation graph
f
but only view models accessed via
navGraphViewModels
, right?
AmbientViewModelStoreOwner
(used by
viewModel()
) is
NavBackStackEntry
.
i
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
@Ian Lake Great news 😄
107 Views