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
What's the cleanest way to achieve this ?
There is the generic to(Function<Single<T>, R>) that allows converting to any type with a function.
Perfect !
Most helpful comment
There is the generic
to(Function<Single<T>, R>)that allows converting to any type with a function.