0

I have a fragment container view to load more than three fragments, each fragment shared by ViewModel using navGraphViewModels

private val viewModel: HomeViewModel by navGraphViewModels(R.id.home_navigation_xml) { defaultViewModelProviderFactory }

How can we get the same instance of ViewModel inside parent activity?

Bincy Baby
  • 3,941
  • 5
  • 36
  • 62
  • Why are you using a navigation graph scoped view model if you want to access it at a larger scope (i.e., the whole activity level)? – ianhanniballake Sep 06 '21 at 02:29

1 Answers1

0

I used the following method to solve my issue.

val viewModel by lazy {
            binding?.homeFragmentContainerView?.findNavController()
                ?.getViewModelStoreOwner(R.id.home_navigation_xml)?.viewModelStore?.let {
                    ViewModelProvider(
                        it,
                        ViewModelProvider.AndroidViewModelFactory.getInstance(application)
                    ).get(HomeViewModel::class.java)
                }
        }
Bincy Baby
  • 3,941
  • 5
  • 36
  • 62