Reputation: 1606
I have API that returns the data by page, something like this:
{
"count": 100,
"offset": 0,
"limit": 25,
"result": [{}, {}, {}...]
}
I need to get all pages - All data (to execute queries with a different "offset":).
Observable<MyResponse> call = RetrofitProvider.get().create(MyApi.class).getData(0, 25); // limit and offset
call.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.doOnNext(<saving data>)
.subscribe(result -> {
}, error -> {
});
I'm trying to use RxAndroid and Retrofit. What is the best way this?
Upvotes: 1
Views: 1487
Reputation: 3711
You can use a publish subject as your source observable, then you keep adding new requests for the next range dynamically.
private Observable<ApiResponse> getData(int start, int end) {
// Get your API response value
return RetrofitProvider.get().create(MyApi.class).getData(0, 25);
}
public Observable<ApiResponse> getAllData() {
final PublishSubject<ApiResponse> subject = PublishSubject.create();
return subject.doOnSubscribe(new Action0() {
@Override
public void call() {
getData(0, SECTION_SIZE).subscribe(subject);
}
}).doOnNext(new Action1<ApiResponse>() {
@Override
public void call(ApiResponse apiResponse) {
if (apiResponse.isFinalResultSet()) {
subject.onCompleted();
} else {
int nextStartValue = apiResponse.getFinalValue() + 1;
getData(nextStartValue, nextStartValue + SECTION_SIZE).subscribe(subject);
}
}
});
}
Upvotes: 2
Reputation: 3083
If you know what the count is going to be you can do something like
Observable<MyResponse> call = Observable.empty();
for (int i=0 ; i<count ; i+=25) {
call.concatWith(RetrofitProvider.get().create(MyApi.class).getData(i, i+25));
}
Upvotes: 0