Nested Observers with LiveData (Observing an observer)

北战南征 提交于 2021-01-29 05:18:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!