如何订阅点击事件,所以异常不会退订? [英] How to subscribe to click events so exceptions don't unsubscribe?

查看:232
本文介绍了如何订阅点击事件,所以异常不会退订?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 RxJava为Android(RxAndroid)和我订阅点击视图的事件,并做一些对他们如下:

I'm using RxJava for Android (RxAndroid) and I subscribe to click events of a view, and do something on them as follows:

subscription = ViewObservable.clicks(view, false)
    .map(...)
    .subscribe(subscriberA);

问题是,每当有一个例外, subscriberA 自动退订,导致下一次单击不触发任何东西。

The problem is whenever there is an exception, subscriberA automatically unsubscribes, leading to the next click not triggering anything.

如何处理异常,所以拦截所有单击事件,无论异常被抛出?

How to handle exceptions so to intercept all the click events regardless of exceptions being thrown?

推荐答案

使用的 重试 方式:

Use retry method:

subscription = ViewObservable.clicks(view, false)
    .map(...)
    .retry()
    .subscribe(subscriberA)

但是,您将不会收到在的onError 任何异常。
为了处理与重试(重新订阅)逻辑使用异常 retryWhen

However, you will not receive any exception in onError. To handle exceptions with retry (resubscribe) logic use retryWhen:

subscription = ViewObservable.clicks(view, false)
    .map(...)
    .retryWhen(new Func1<Observable<? extends Notification<?>>, Observable<?>>() {

        @Override
        public Observable<?> call(Notification errorNotification) {
            Throwable throwable = errorNotification.getThrowable();
            if (errorNotification.isOnError() && handleError(throwable)) {
                // return the same observable to resubscribe
                return Observable.just(errorNotification);
            }
            // return unhandled error to handle it in onError and unsubscribe
            return Observable.error(throwable);
        }

        private boolean handleError(Throwable throwable) {
            // handle your errors
            // return true if error handled to retry, false otherwise
            return true;
        }
    }
    .subscribe(subscriberA)

这篇关于如何订阅点击事件,所以异常不会退订?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆