How to give same instance of ViewModel to both the Parent and Child fragment
Implement fragment-ktx in your app -> build.gradle:
implementation 'androidx.fragment:fragment-ktx:1.2.5
If you are using Navigation Component (https://developer.android.com/guide/navigation)
In the parentFragment, you can get the viewModel like this:
private val viewModel by viewModels<DemoViewModel>()
And then when you need that viewModel in the childFragment you can get it this way:
private val viewModel by viewModels<DemoViewModel>({requireGrandParentFragment()})
the requireGrandParentFragment() is a custom extension of Fragment:
fun Fragment.requireGrandParentFragment() = this.requireParentFragment().requireParentFragment()
If you are not using Navigation Component
you can access it like this:
private val viewModel by viewModels<DemoViewModel>({requireParentFragment()})
Using Fragment-ktx we can do as In **ParentFragment**
private val viewModel: DemoViewModel by viewModels()
And
In ChildFragment
private val viewModel: DemoViewModel by viewModels(
ownerProducer = { requireParentFragment() }
)
Doing this we can get same instance of ViewModel in Parent Fragment and ChildFragment
add dependencies in app -> build.gralde
implementation 'androidx.fragment:fragment-ktx:1.1.0
Create your ViewModel
with Activity
scope. Then all Fragment
within that Activity
will get same ViewModel
instance.
Check official ViewModelProviders reference. You can create ViewModel
with both Activity
and Fragment
scope.
ViewModelProvider of (FragmentActivity activity)
Creates a ViewModelProvider, which retains ViewModels while a scope of given Activity is alive. More detailed explanation is in ViewModel.
and
ViewModelProvider of (Fragment fragment)
Creates a ViewModelProvider, which retains ViewModels while a scope of given fragment is alive. More detailed explanation is in ViewModel.
Sample code for creating ViewModel
From Activity:
movieListViewModel = ViewModelProviders.of(this).get(MovieListViewModel.class);
From Fragment:
movieListViewModel = ViewModelProviders.of(getActivity()).get(MovieListViewModel.class);