Using flatMap in RxJava 2.x

时光怂恿深爱的人放手 提交于 2019-12-04 09:03:06

My solution

import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public void getAllUsers(){

    AtomicReference<String> cache = new AtomicReference<>();
    AtomicBoolean hasMore = new AtomicBoolean(true);

    io.reactivex.Observable.just(0)
        // getting the first 50 users
        .flatMap(users1-> service.getUsers( cache.get() ))

        // scheduler
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())

        // re-call variable
        .repeatUntil(() -> !hasMore.get())

        .subscribe(new Observer<DataResponse>() {
            @Override
            public void onSubscribe(Disposable d) { // on subscribe }

            @Override
            public void onNext(DataResponse response) {

                // saving boolean (If there are more users)
                hasMore.set(response.hasNextCursor());

                // saving next cursor
                cache.set(response.endCursor());

                // adding the new 50 users
                addToList(response.getUsers());

            }

            @Override
            public void onError(Throwable e) {// error}

            @Override
            public void onComplete() {// complete}
        });

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!