调用onNext

时间:2016-01-15 20:31:07

标签: java rx-java

这是我在PublishSubject中使用的代码。

public class RxPager {


private int startPage; //starting page number
private final int initialPageCount; //number of pages to provide when requestNext() is called
private final PublishSubject<Integer> requests = PublishSubject.create();
private int requestedCount; //basically keeps track of the last page that was requested

public RxPager() {
    this(1, 1); // by default start at page #1
}

public RxPager(int startPage, int initialPageCount) {
    this.initialPageCount = initialPageCount;
    this.startPage = startPage;
}

public void decrementRequestedCount(){
    requestedCount--;
}

public void requestNext(int page) {
    requests.onNext(page);
}

public Observable<Integer> pages() {
    return requests
            .concatMap(new Func1<Integer, Observable<Integer>>() {
                @Override
                public Observable<Integer> call(Integer targetPage) {
                    //check if we have already provided this page -- if targetPager is less than requestedCount it means this page has already been provided
                    if (targetPage <= requestedCount) {
                        return Observable.empty();
                    }
                    else {
                        //returns each page one by one and adds an offset to them
                        return Observable.range(requestedCount, targetPage - requestedCount)
                                .flatMap(new Func1<Integer, Observable<Integer>>() {
                                    @Override
                                    public Observable<Integer> call(Integer page) {
                                        return Observable.just(page + startPage); // offset the page number
                                    }
                                });
                    }
                }
            })
            .startWith(
                    Observable.range(0, initialPageCount)
                            .flatMap(new Func1<Integer, Observable<Integer>>() {
                                @Override
                                public Observable<Integer> call(Integer page) {
                                    return Observable.just(page + startPage); // offset the page number
                                }
                            })
            )
            .doOnNext(new Action1<Integer>() {
                @Override
                public void call(Integer it) {
                    //make sure to increment requested count so that the same page can't be requested
                    requestedCount = it - startPage + 1; //need to offset here too
                }
            });
}

}

我正在尝试创建一个分页机制,我可以在其中调用rxPager.requestNext(page)并使用返回的值,我将其用于使用API​​进行分页。但是,如果API返回错误,我会调用rxPager.decrementRequestedCount(),然后使用此rxPager.requestNext(samePage)重新请求同一页面。然而,似乎当我这样做时,没有任何事情发生。它甚至从未命中if (targetPage <= requestedCount)

0 个答案:

没有答案