if error occurred in doAfterSuccess Observer onError not call

Viewed 865

When I use retrofit with Single if error throw from doAfterSuccess observer onError not call and app crash(UndeliverableException) but when I create Single myself and throw an exception from a doAfterSuccess observer onError call.

Why doAfterSuccess behave two different way?.

1 Answers

The Single protocol is defined as follows: onSubscribe (onSuccess | onError)?. In words, if onSuccess is called, onError can't be called and vice versa. The doAfterSuccess can nowhere to go with respect to this protocol and to avoid losing possibly important exceptions, it is routed to the global error handler. The wiki has more detailed explanations about it.

If you find yourself wanting to invoke onError after an onSuccess, you are probably using the wrong type. The Observable protocol allows calling onError from whitin or after an onNext.

Alternatively, use try-catch in your unreliable onSuccess handler and call the same code as you'd call from onError.

Single.just(1)
.doAfterSuccess(v -> {
    try {
       process(v);
    } catch (Throwable ex) {
       reportError(ex);
    }
})
.subscribe(v -> { /* ok */ }, e -> { reportError(e); });
Related