当我在NavigationView中按下项目时,我将调用getSupportFM并加载片段。在片段中,我附加了ViewModel,并在构造函数中,然后从网络加载数据,这次是在方法.doOnNext
中将其保存在Realm数据库中。
public MyViewModel() {
repository = new MyRepository();
realm = Realm.getDefaultInstance();
liveData = new LiveRealmResults<>(realm.where(MyClass.class).findAllAsync());
}
我的网络请求:
apiInterface.getMyData(page)
.subscribeOn(Schedulers.io())
.doOnNext(myDataRequest -> {
if (myDataRequest.getMyData().size() != 0) {
List<MyData> myData= myDataRequest.getMyData();
try (Realm realm = Realm.getDefaultInstance()) {
realm.executeTransaction(r -> r.insertOrUpdate(myData));
}
}
})
.observeOn(AndroidSchedulers.mainThread())
我的片段:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//we should to do this.
//https://developer.android.com/jetpack/arch/livedata#the_advantages_of_using_livedata
viewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
viewModel.getMyLiveData().observe(this, stateObserver);
}
观察者:
private Observer<List<MyData>> stateObserver = new Observer<List<MyData>>() {
@Override
public void onChanged(@Nullable List<MyData> myData) {
if (myData.size() != 0) {
progressBar.setVisibility(View.GONE);
adapter.updateAdapter(myData);
}
}
};
但是,如果我删除这一行,当我在navigationView的片段之间进行交换时,DrawerLayout不会太迟。第一次,我从网络中加载了20个元素。
我花了两天时间来修复它,但我不知道该怎么做。
viewModel.getMyLiveData().observe(this, stateObserver);