Alexander Hramov
Alexander Hramov

Reputation: 2260

How to organise chain of async calls in RxJava2 way

I have next code wrapped in AsyncTask class

        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                if (NetworkUtils.isNetworkConnected(mContext))
                    mIndicatorTable.sync().blockingGet();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            } finally {
                try {
                    final MobileServiceList<IndicatorModel> results = mIndicatorTable.table().read(null).blockingGet();
                    if (isViewAttached()) {
                        getMvpView().refreshIndicatorList(results);
                        getMvpView().hideLoading();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        };

mIndicatorTable.sync() and mIndicatorTable.table().read(null) both returns Single<Boolean>. mIndicatorTable.sync() - syncing local storage with remote one, if network is unavailable then we just read from local storage using mIndicatorTable.table().read(null) when network is ready - we execute syncing and then read from local storage (we don't care if syncing canceled or interrupted). And after all we should call View to refresh RecycleView. How it can be implemented with RxJava2?

#UPDATE

Working version

getDataManager().syncAll()
     .onErrorResumeNext(Single.just(false))
     .flatMap(list -> toSingle(mIndicatorTable.getTable().read(null)))
     .subscribeOn(Schedulers.newThread())
     .observeOn(AndroidSchedulers.mainThread())
     .subscribe(results -> {
        if (isViewAttached()) {
            getMvpView().refreshIndicatorList(results);
            getMvpView().hideLoading();
        }
     })

Upvotes: 1

Views: 1463

Answers (1)

Geoffrey Marizy
Geoffrey Marizy

Reputation: 5531

rx-java make chaining async call easy by just calling .flatMap().

mIndicatorTable.sync()
        .flatMap(new Function<Boolean, SingleSource<MobileServiceList<IndicatorModel>>>() {
            @Override
            public SingleSource<MobileServiceList<IndicatorModel>> apply(Boolean aBoolean) throws Exception {
                return mIndicatorTable.table().read(null);
            }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(...)

But you want to proceed the sync() call in another thread and RecycleView could only be accessed from main thread. That's where rx-android come in handy. .subscribeOn(Schedulers.io()) instantiate the stream in another thread and .observeOn(AndroidSchedulers.mainThread()) ensure that statements below this line (here, .subscribe(...)) are executed in the main thread.

Upvotes: 1

Related Questions