从Fragment观察MediatorLiveData会导致配置更改后多次触发

时间:2020-10-26 21:45:10

标签: android-fragments android-livedata android-architecture-components android-jetpack mediatorlivedata

我正在从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实例中不发生。

0 个答案:

没有答案