How to share ViewModel between Parent fragment and fragment inside child fragment

Viewed 1518

I have parent Fragment that contains child fragment. Inside child fragment I have ViewPager with fragments. My question is how can I share ViewModel between parent child and fragments in viewpager and makeing Viewmodel visible only on ParentFragment scope?

2 Answers

what do you mean when you say "visible only on ParentFragment scope"?

According Google's document, there is one way that you can share ViewModel. Check this document: https://developer.android.com/topic/libraries/architecture/viewmodel#sharing Shortly, your parent fragment and child fragment will use the same ViewModel. Your parent fragment will call the function of ViewModel to change the data, your child fragment just observer the LiveData of ViewModel.

You can place your sharedViewModel inside your Activity. Then you can access it from every fragment which in attached to this activity with this code:

(requireActivity() as MainActivity).viewModel;

With this approach, you can set data from one fragment and observe data from another fragment. So, you enable communication between two fragments.

Setting data:

viewModel.liveDataObject.value = value

Observing data:

viewModel.liveDataObject.observe(viewLifecycleOwner) {}
Related