theanilpaudel
theanilpaudel

Reputation: 3488

Retry observable till some conditions are met using RxJava for Android

I have setup Retrofit with Rxjava like this

    Retrofit retrofit = ApiManager.getAdapter();
        final SplashApiInterface splashApiInterface = retrofit.create(SplashApiInterface.class);
        final Observable<List<Data>> observable = splashApiInterface.getTenData(offset);
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).unsubscribeOn(Schedulers.io())

                .subscribe(new Subscriber<List<Data>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(List<Data> dataList) {

                          splashListener.takeDataToPres(dataList);
                        }
                    }
                });

My requirement is like this, the api generates List of 10 datas at a time and I need to query all those data increasing the offset value by 10 and then append those datas to list. How can I achieve this using RxJava for android?

Upvotes: 3

Views: 471

Answers (1)

Maksim Ostrovidov
Maksim Ostrovidov

Reputation: 11058

You can do it like this:

Observalbe.range(0, 100) // specify offset range
    .filter(i -> i%10==0) // takes only a multiples of ten
    .concatMap(i -> splashApiInterface.getTenData(i)) // makes subsequent API calls for each offset value
    .flatMap(data -> Observable.from(data)) // flattens each list
    .toList() // and collects all items to a single list
    ... // apply schedulers, subscribe and process your result list

You can make all of your API calls fire at the same time. To achieve it - just replace concatMap with flatMap.

Code without lamdas (RxJava 1.2.4):

Observable.range(0, 100)
            .filter(new Func1<Integer, Boolean>() {
                @Override
                public Boolean call(Integer i) {
                    return i % 10 == 0;
                }
            })
            .concatMap(new Func1<Integer, Observable<? extends List<Data>>>() {
                @Override
                public Observable<? extends List<Data>> call(Integer i) {
                    return splashApiInterface.getTenData(i);
                }
            })
            .flatMap(new Func1<List<Data>, Observable<? extends Data>>() {
                @Override
                public Observable<? extends Data> call(List<Data> data) {
                    return Observable.from(data);
                }
            })
            .toList()

Upvotes: 1

Related Questions