'How to use navGraphViewModels in Activity (Not in Fragment)

In Fragment, we can use ViewModel scoped to navigation Graph.

private val viewModel: ViewModel by navGraphViewModels(R.id.youNavGraphID)

But how to create ViewModel with navGraph scope in Activity? Or is it any way to make the ViewModel scoped to navigation graph in Activity? I need to recreate the ViewModel object instance after the navigation graph is destroyed.

Thanks.



Solution 1:[1]

This is a very late answer but hopefully it helps someone else.

You can use a ViewModelProvider with the ViewModelStoreOwner of the NavigationController.

Basically like this:

val myViewModel = ViewModelProvider(
    navController.getViewModelStoreOwner(navGraphId), 
    defaultViewModelProviderFactory
)[MyViewModel::class.java]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juancamilo87