我正在从MediatorLiveData
的{{1}}内部观察一个onViewCreated(...)
对象。我使用Fragment
作为getViewLifecycleOwner()
。轮换或其他配置更改后,似乎LifecycleOwner
被一次又一次注册,导致检索数据的次数增加。
以下是Oberver
的一些代码:
Fragment
这是public class MyFragment extends Fragment {
...
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
UserViewModel userViewModel = new ViewModelProvider(requireActivity()).get(UserViewModel.class);
LiveData<RatedProduct> userLiveData = userViewModel.getRatedProductLiveData();
userLiveData.observe(getViewLifecycleOwner(), new Observer<RatedProduct>() {
@Override
public void onChanged(RatedProduct ratedProduct) {
// doing some stuff
}
});
}
}
:
ViewModel
如何避免多次public class UserViewModel extends ViewModel {
...
private UserRatingsLiveData mUserRatingsLiveDate;
private MediatorLiveData<RatedProduct> mLiveDataCollector = new MediatorLiveData<> ();
public UserViewModel() {
...
this.mUserRatingsLiveDate = new UserRatingsLiveData(...);
this.mLiveDataCollector.addSource(this.mUserRatingsLiveDate, new RatedProductObserver());
}
@NonNull
public LiveData<RatedProduct> getRatedProductLiveData() {
return this.mLiveDataCollector;
}
private class RatedProductObserver implements Observer<UserRating> {
public void onChanged(UserRating userRatings) {
// doing some stuff
}
}
注册。也许我想念一些未注册的信息。我认为使用Observer
应该避免这种情况。
通过以下方式修改getViewLifecycleOwner()
会有所帮助,但是我不确定这是否正确:
getRatedProductLiveData()
添加:
该问题仅在@NonNull
public LiveData<RatedProduct> getRatedProductLiveData() {
this.mLiveDataCollector = new MediatorLiveData<> ();
this.mLiveDataCollector.addSource(this.mUserRatingsLiveDate, new RatedProductObserver());
return this.mLiveDataCollector;
}
处发生,而在其他MediatorLiveData
实例中不发生。