我知道如何处理Retrofit响应,但我在使用rx java从REST API处理分页时遇到问题。
背景
我正在使用的其他api通过标题中下一页的链接给出了以下回复:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Link: <http://some-endpoint.com/pictures?page=2>; rel="next"
Vary: Accept
X-Total-Count: 80
[
{
"id": 3,
"url": "",
"picture": {
"id": 6,
"url": "",
"name": "Chrysler"
},
"location": {
"type": "Point",
"coordinates": [
10.108956,
41.389576000000005
]
}
},
{
"id": 4,
"url": "",
"picture": {
"id": 26,
"url": "",
"name": "Douglas Aircraft"
},
"location": {
"type": "Point",
"coordinates": [
10.1977759999999997,
41.426645
]
}
},
...
}
正确的知道我设法通过以下代码获取第2页的分页请求但我不知道如何制作这些分页请求,直到没有&#34; next&#34;响应上的标题链接,以便我能够将所有数据中的所有数据保存到数据库中。
private Observable<List<PictureEntity>> getPictures(final LocationEntity locationEntity) {
if (getDataFromServer()) {
return mApiService.getPictures()
.concatMap(new Func1<Response<List<Picture>>, Observable<Response<List<Picture>>>>() {
@Override
public Observable<Response<List<Picture>>> call(Response<List<Picture>> listResponse) {
String link = NetworkUtil.getNextLinkPaginate(listResponse.headers().get("Link"));
Timber.i(link);
return Observable.just(listResponse)
.concatWith(mApiService.getPicturesPaginate(link))
.reduce(new Func2<Response<List<Picture>>, Response<List<Picture>>,
Response<List<Picture>>>() {
@Override
public Response<List<Picture>> call(Response<List<Picture>> listResponse,
Response<List<Picture>> listResponse2) {
listResponse.body().addAll(listResponse2.body());
return listResponse;
}
});
}
})
.concatMap(new Func1<Response<List<Picture>>, Observable<List<PictureEntity>>>() {
@Override
public Observable<List<PictureEntity>> call(Response<List<Picture>> listResponse) {
List<PictureEntity> pictureEntities =
mPictureDataMapper.transformToEntity(listResponse.body());
mDatabaseHelper.setPictureEntity(pictureEntities).subscribe();
return mDatabaseHelper.getNearbyPicturesEntity(locationEntity);
}
});
} else {
return mDatabaseHelper.getNearbyPicturesEntity(locationEntity);
}
}
有关如何处理此类请求的任何建议?也许.takeUntil运营商?
答案 0 :(得分:-2)
您可以使用concatMap进行一些递归。
Observable<List<PointOfSaleEntity>> getPointsOfSalePaginateUntilEnd(String link) {
if (link.equals("")) {
return Observable.empty();
} else {
return mApiService.getPointsOfSalesPaginate(link)
.concatMap(listResponse -> Observable.concat(Observable.just(listResponse),mApiService.getPointsOfSalesPaginate(NetworkUtil.getNextLinkPaginate(listResponse.headers().get("Link")))));
}
}
Observable<List<PointOfSaleEntity>> getPointsOfSalePaginateUntilEnd() {
return mApiService.mApiService.getPointsOfSales()
.concatMap(listResponse -> Observable.concat(Observable.just(listResponse),mApiService.getPointsOfSalesPaginate(NetworkUtil.getNextLinkPaginate(listResponse.headers().get("Link")))));
}