I'm having issues handling paging with RXJava2. I tried to follow this post from SO but it was dated. I was hoping to get a more up to date answer. I'm using Retrofit and I'm trying to page a third party API till I have all of the results. The response is below but I pretty much want to through all pages and combine all results.
Currently my code is as follows:
public Observable<WatchList> syncWatchlistSection(String accountId) {
String sessionToken = mLocal.getSessionId();
int page = 1;
return getWatchlistFromServerHelper(sessionToken, accountId, page).concatMap(new Function<WatchList, ObservableSource<? extends WatchList>>() {
@Override
public ObservableSource<? extends WatchList> apply(WatchList watchList) throws Exception {
return Observable.fromArray(watchList);
}
});
}
And in the same file the helper file similar to the previous SO post.
private Observable<WatchList> getWatchlistFromServerHelper(String sessionToken, String accountId, int page) {
return mRestAPI.fetchWatchlistOnServer(sessionToken, accountId, page).concatMap(new Function<WatchList, Observable<WatchList>>() {
@Override
public Observable<WatchList> apply(WatchList watchList) throws Exception {
if (watchList.getPage() == watchList.getTotalPages()) {
return Observable.just(watchList);
}
return Observable.just(watchList).concatWith(getWatchlistFromServerHelper(sessionToken, accountId, page + 1));
}
});
}
I'm calling this via a subscribe on my activity.
mSectionLogic.syncWatchlistSection(String.valueOf(account.getId()))
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<WatchList>() {
... so on ...
This works but doesn't handle the paging. The response looks something like:
{
page: 1,
totalPages: 5,
results: []
}
What I've done is it should return when page == totalPages
. Except it doesn't combine the previous results and just returns the last page of results.
mRestAPI.fetchWatchlistOnServer is the Retrofit2 Get request that returns Observable<Watchlist>
.
What am I doing wrong? How do I combine results with Observable? Preferably not in Lamda notation.
Other resources I looked at: - android rxjava2/retrofit2 chaining calls with pagination token