5

Inside Activity you can get a ViewModel scoped to that Activity like this:

val viewModel = ViewModelProviders.of(this)[ViewModel::class.java] //deprecated way
val viewModel = ViewModelProvider(this)[ViewModel::class.java]
//or
val viewModel by viewModels<ViewModel>()

Similarly in a Fragment you can get a ViewModel by

//scoped to parent Activity
val viewModel: ViewModel by activityViewModels()

//scoped to parent Fragment
val viewModel: ViewModel by viewModels({ requireParentFragment() })

//scoped to navigation graph
val viewModel: ViewModel by navGraphViewModels(R.id.login_graph)

Now if I try to access a ViewModel inside Activity which is scoped to a navigation graph then there is no helper method so I have to do

val viewModel by lazy {
    ViewModelProvider(findNavController(R.id.nav_host_fragment)
            .getViewModelStoreOwner(R.id.your_graph).viewModelStore,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
    ).get(ViewModel::class.java)
}

Is there a helper method that I have missed? Do I have to access it via navigation graph scope? Can I just use Activity scope to access the same ViewModel?

M-Wajeeh
  • 17,204
  • 10
  • 66
  • 103
  • why should the activity know about child's ViewModel scoped to the child? see if this helps https://stackoverflow.com/questions/57741008/accessing-graph-scoped-viewmodel-of-child-navhostfragment-using-by-navgraphviewm – denvercoder9 Sep 19 '19 at 08:02

0 Answers0