Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scope a view model to a parent fragment?

So I'm using the new navigation component (with the one activity principle) and communicating between each fragment using shared view models, however, I've come to a point where I sometimes need to clear the view model but I can't find a good place to clear it. But tbh I think rather than trying to clear it myself, I should really be allowing the framework to do it for me, but it doesn't because the view models are shared and scoped to the activity, but I think I can scope them to a parent fragment, I made a drawing to illustrate what I'm trying to do.my navigation flow so I only want to clear the 2 view models when I navigate back from "Child 1 Child a" currently the view models are never cleared, trying to get the view model currently by calling 'this' in the fragment and getParentFragment in the child doesn't work, can anyone provide an example?

EDIT

It looks like I was already doing something similar but it's not working in my case so I will add some code, here is how I access the first view model in the parent fragment

model = ViewModelProviders.of(this).get(RequestViewModel.class);

and then in the child fragment, I'm doing this

requestViewModel = ViewModelProviders.of(getParentFragment()).get(RequestViewModel.class);

but it's not keeping the data between them, they both have observers attached

like image 484
martinseal1987 Avatar asked Dec 17 '18 14:12

martinseal1987


2 Answers

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() }
)
like image 197
Alok Mishra Avatar answered Sep 30 '22 15:09

Alok Mishra


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

like image 33
martinseal1987 Avatar answered Sep 30 '22 17:09

martinseal1987