How to subscribe to click events so exceptions don't unsubscribe?

て烟熏妆下的殇ゞ 提交于 2020-01-15 06:27:07

问题


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);

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?


回答1:


Use retry method:

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

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)


来源:https://stackoverflow.com/questions/26154236/how-to-subscribe-to-click-events-so-exceptions-dont-unsubscribe

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