问题
I have a case where I have BottomNavigationView where fragments are shown/hidden instead of adding/replacing, therefore they do not go through their lifecycle every time.
Fragment 1 is observing one database table, Fragment 2 is observing a different one.
My goal is to call the onChanged of Fragment 2 when onChanged of Fragment 1 is called.
A stupid and naive solution that worked was to set up the observer of Fragment 1 in Fragment 2 and inside it call another observer:
mFragment1ViewModel1.getData().observe(this, new Observer<Fragment1Data>() {
@Override
public void onChanged(Fragment1Data fragment1Data) {
if(fragment1Data != null){
mFragmentViewModel2.getData().observe(SomeClass.this, new Observer<Fragment2Data>() {
@Override
public void onChanged(@Nullable Fragment2Data fragment2Data) {
// Do some stuff...
}
});
}
}
});
Could someone tell me what would be a good solution in this case and the implications of the solution mentioned above?
回答1:
LiveData 1 is to tell me when it's onChanged method has been triggered, then I want to execute the onChanged of LiveData 2
That actually sounds like it's just
Transformations.switchMap(liveData1, (x) -> { return liveData2; })
.observe(...
来源:https://stackoverflow.com/questions/56518217/nested-observers-with-livedata-observing-an-observer