Search code examples
androidnavigationviewmodelandroid-viewmodel

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

  • 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]