Jason Ankers

    Jason Ankers

    1 year ago
    Is it possible to scope a viewmodel to a navigation graph with navigation-compose?
    f

    fmasa

    1 year ago
    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
    Jason Ankers

    Jason Ankers

    1 year ago
    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

    1 year ago
    Don't know about that. I use Koin right now 😕
    FunkyMuse

    FunkyMuse

    1 year ago
    If you're using navigation compose by default they're scoped to the navigation graph
    f

    fmasa

    1 year ago
    but only view models accessed via
    navGraphViewModels
    , right?
    AmbientViewModelStoreOwner
    (used by
    viewModel()
    ) is
    NavBackStackEntry
    .
    i

    Ian Lake

    1 year ago
    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
    Jason Ankers

    Jason Ankers

    1 year ago
    @Ian Lake Great news 😄