带LiveData的嵌套观察者(观察者) [英] Nested Observers with LiveData (Observing an observer)
问题描述
在某些情况下,我有BottomNavigationView,其中显示/隐藏片段而不是添加/替换片段,因此它们不会每次都经历其生命周期.
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.
片段1 观察一个数据库表,片段2 观察另一数据库表.
Fragment 1 is observing one database table, Fragment 2 is observing a different one.
我的目标是在调用 Fragment 1 的onChanged时调用 Fragment 2 的onChanged.
My goal is to call the onChanged of Fragment 2 when onChanged of Fragment 1 is called.
一种有效的愚蠢而幼稚的解决方案是在片段2 中设置片段1 的观察者,并在其中调用另一个观察者:
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?
推荐答案
LiveData 1告诉我何时触发了onChanged方法,然后我要执行LiveData 2的onChanged
LiveData 1 is to tell me when it's onChanged method has been triggered, then I want to execute the onChanged of LiveData 2
这听起来好像只是
Transformations.switchMap(liveData1, (x) -> { return liveData2; })
.observe(...
这篇关于带LiveData的嵌套观察者(观察者)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!