Rxjava: 2.x: Transformers from Observable to Single

Created on 8 Mar 2017  路  2Comments  路  Source: ReactiveX/RxJava

I'm refactoring some code, and I would like to have a reusable way to show the progress of a download and a button to cancel it. The client side is only interested to know if the download was completed (so it can chain other things after) or not. Here's my code right now :

public Single<Boolean> showCancellableDownload(Observable<Progress> download) {
        Completable cancel = mView.showLoading();

        return download
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(progress -> {
                    mView.showLoadingProgress(progress.percent());
                })
                .ignoreElements()
                .toSingleDefault(true)
                .takeUntil(cancel)
                .onErrorResumeNext(throwable -> {
                    if (throwable instanceof CancellationException) {
                        Timber.w("showCancellableDownload: CancellationException");
                        return Single.just(false);
                    } else
                        return Single.error(throwable);
                })
                .doOnSuccess(aBoolean -> mView.hideLoading())
                .doOnError(throwable -> mView.hideLoading());
    }

As said Dan Lew in this article, I'd better use a Transformer, but existing classes only allows to transform to the same type (Observable -> Observable, Single -> Single).

What's the cleanest way to achieve this ?

2.x Question

Most helpful comment

There is the generic to(Function<Single<T>, R>) that allows converting to any type with a function.

All 2 comments

There is the generic to(Function<Single<T>, R>) that allows converting to any type with a function.

Perfect !

Was this page helpful?
0 / 5 - 0 ratings