我正在尝试使用新的Android架构组件,但我很困惑。
我创建了一个ViewModel类
public class BuyViewModel extends ViewModel {
private BuyRepository buyRepository;
private LiveData<Adverts> advertsLiveData;
private boolean isLoading;
private int currentPage;
@Inject
public BuyViewModel(BuyRepository buyRepository) {
this.buyRepository = buyRepository;
}
public void init(int currentPage) {
this.currentPage = currentPage;
if (this.advertsLiveData != null) {
return;
}
Timber.tag("logi").d("BuyViewModel > init -> ");
advertsLiveData = buyRepository.getAdverts(currentPage);
}
public LiveData<Adverts> getAdvertsLiveData() {
return advertsLiveData;
}
}
在LifeCycleFragment中观察LiveData
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
buyViewModel = ViewModelProviders.of(this, viewModelFactory).get(BuyViewModel.class);
buyViewModel.init(1);
buyViewModel.getAdvertsLiveData().observe(this, adverts -> {
Timber.tag("logi").d("BuyFragment > onActivityCreated -> ");
assert adverts != null;
adapter.addMoreAdverts(adverts.getResults());
});
setupViews();
}
但是当我将这个片段替换为另一个片段并切换回此片段时,方法onChange
被调用了两次,并在rvAdapter
中添加了相同数据的两个部分。
答案 0 :(得分:4)
我解决了这个问题! 当我创建我的ViewModel类时,我传递了#34;这个&#34;方法
中的第一个参数 buyViewModel = ViewModelProviders.of(**this**, viewModelFactory).get(BuyViewModel.class);
但我需要传递&#34; getActivity()&#34;,代码看起来像那样
buyViewModel = ViewModelProviders.of(**getActivity()**,viewModelFactory).get(BuyViewModel.class);
答案 1 :(得分:0)
当你经过&#34;这个&#34;内部片段 - 它需要你的片段的实例。更改配置后,片段的onDestroy()不会调用(应该执行unsubsription),而只调用onDestroyView()。因此,当您传递活动的实例时,它会被取消,因为您的活动的onDestroy()被调用了。