使用 RxJava 处理分页 [英] Handle Paging with RxJava
问题描述
我在 Android 应用程序上使用 Retrofit + RxJava,并问自己如何处理 API 分页以链接调用,直到检索到所有数据.是这样的:
I'm using Retrofit + RxJava on an Android app and am asking myself about how to handle the API pagination to chain calls until all data is being retrieved. Is something like this:
Observable<ApiResponse> getResults(@Query("page") int page);
ApiResponse 对象具有简单的结构:
The ApiResponse object has a simple structure:
class ApiResponse {
int current;
Integer next;
List<ResponseObject> results;
}
API 将返回 next 值直到最后一页.
The API will return a next value until is last page.
有什么好的方法可以实现这一目标吗?尝试结合一些 flatMaps(),但没有成功.
There's some good way to achieve this? Tried to combine some flatMaps(), but had no success.
推荐答案
您可以递归建模:
Observable<ApiResponse> getPageAndNext(int page) {
return getResults(page)
.concatMap(new Func1<ApiResponse, Observable<ApiResponse>>() {
@Override
public Observable<ApiResponse> call(ApiResponse response) {
// Terminal case.
if (response.next == null) {
return Observable.just(response);
}
return Observable.just(response)
.concatWith(getPageAndNext(response.next));
}
});
}
然后,消费它,
getPageAndNext(0)
.concatMap(new Func1<ApiResponse, Observable<ResponseObject>>() {
@Override
public Observable<ResponseObject> call(ApiResponse response) {
return Observable.from(response.results);
}
})
.subscribe(new Action1<ResponseObject>() { /** Do something with it */ });
这应该会为您提供一个 ResponseObject
流,它将按顺序到达,并且很可能以页面大小的块的形式到达.
That should get you a stream of ResponseObject
that will arrive in order, and most likely arrive in page-size chunks.
这篇关于使用 RxJava 处理分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!