How to scope a view model to a parent fragment?
So, as per @martin's proposed solution derives that even if One/Many Fragments added as Child inside Parent Fragment, Navigation component provides same Fragment manager to both fragments.
Meaning that even if fragments are added as parent-child hierarchy, they'll share same Fragment manager from Navigation component (might be bug in this library ?) & so that ViewModels
are not shared due to this dilemma when using getParentFragment()
instance for ViewModelProvider
inside child fragment.
So, one quick solution to share ViewModels
would be getting instance of Parent fragment from Fragment manager using below line for both parent & child fragments :
ViewModelProviders.of(getParentFragment()).get(SharedViewModel.class); // using this in both parent amd child fragment would do the trick !
Using Fragment-ktx libr in your app you can get viewModel as below in your app-> build.gradle
implementation 'androidx.fragment:fragment-ktx:1.1.0'
// get ViewModel in ParentFragment as
private val viewModel: DemoViewModel by viewModels()
// get same instance of ViewModel in ChildFragment as
private val viewModel: DemoViewModel by viewModels(
ownerProducer = { requireParentFragment() }
)
Ok so using this in the parent
model = ViewModelProviders.of(this).get(RequestViewModel.class);
and this in the child
requestViewModel = ViewModelProviders.of(getParentFragment()).get(RequestViewModel.class);
were giving me different hashcodes but the same IDs and it seems to be because of the navigation component, if i change them both to getParentFragment then it works, so i think the component is replacing fragments instead of adding them here, many thanks to @WadeWilson and @JeelVankhede