是否有任何好的模式使用RxJava来处理离线和在线的分页。目前,我正在使用这种模式,代码看起来很脏。我想做的是Page 1 Offline => Page 1 Online => Page 2离线=> Page 2 Online..etc。直到页面结束。每个离线呼叫都会添加到在线呼叫将更新页面中的项目的列表中。
public void loadData() {
paginator = PublishSubject.create();
paginator.concatMap(new Function<Integer, ObservableSource<Response>>() {
@Override public ObservableSource<Response> apply(Integer integer)
throws Exception {
Request request = new Request();
request.page = integer;
return NetworkRequestManager.getInstance()
.getData(request)
.subscribeOn(Schedulers.newThread());
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ResponseSubscriber());
mEndlessRecyclerAdapter.onDataReady(true);
}
在NetWorkRequestManager类中,我使用以下代码
public Observable<Response> getData(final Request request) {
return dataService.getOnlineData(request)
.publish(networkResponse -> Observable.merge(networkResponse, dataService.getOfflineData(request).takeUntil(networkResponse)));
}
数据加载成功时。
@Subscribe public void onDataLoaded(Response response) {
if (response.getCurrentPage() == 1) {
mAdapter.setItemList(items);
} else if (!response.data.isEmpty()) {
if (response.isFromOffline) {
mAdapter.addItemList(response.data);
wasOfflineEmpty = false;
} else if (wasOfflineEmpty) {
mAdapter.addItemList(response.data);
} else {
mAdapter.updateItemList(response.data);
}
} else if (response.data.isEmpty() && response.isFromOffline) {
wasOfflineEmpty = true;
}
mEndlessRecyclerAdapter.onDataReady(response.data.size() != 0);
}
正如您所看到的,OnDataLoaded方法中有很多样板文件。是否有更好或推荐的方法来减少样板?