How to handle paging with RxJava?

前端 未结 4 1028
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 14:48

I\'m looking into converting my android app to use Rxjava for network requests. I currently access a webservice similar to:

getUsersByKeyword(String query, int l         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 15:38

    It was hard rock!) So we have request to network:
    getUsersByKeyword(String query, int limit, int offset)
    and this request return for example
    List< Result >
    If we use RetroFit for networking that request will look:
    Observable< List< Result >> getUsersByKeyword(String query, int limit, int offset)
    As result we want to get all Result from server.
    So it will look like this

    int page = 50;
    int limit = page;
    Observable
                    .range(0, Integer.MAX_VALUE - 1)
                    .concatMap(new Func1>>() {
                        @Override
                        public Observable> call(Integer integer) {
                            return getUsersByKeyword(query, integer * page, limit);
                        }
                    })
                    .takeWhile(new Func1, Boolean>() {
                        @Override
                        public Boolean call(List results) {
                            return !results.isEmpty();
                        }
                    })
                    .scan(new Func2< List, List, List>() {
                        @Override
                        public List call(List results, List< Result> results2) {
                            List list = new ArrayList<>();
                            list.addAll(results);
                            list.addAll(results2);
                            return list;
                        }
                    })
                    .last()
                    .subscribe(new Subscriber>() {
                        @Override
                        public void onCompleted() {
                        }
    
                        @Override
                        public void onError(Throwable e) {
    
                        }
    
                        @Override
                        public void onNext(List results) {
                        }
                    });
    

    Code was TESTED!

提交回复
热议问题