Prevent OnErrorNotImplementedException

WonderCsabo picture WonderCsabo · Nov 5, 2015 · Viewed 13.6k times · Source

I want to achieve that if i call the Obervable.subscribe(Action1) method, it does not throw OnErrorNotImplementedException anywhere, but if i call Obervable.subscribe(Action1, Action1), the second action is called when an error is raised as normal. I tried two ways:

.onErrorResumeNext(Observable.empty())

This way OnErrorNotImplementedException is not thrown, however if i pass also the second action, the action is never called either.

Second:

.lift(new Observable.Operator<T, T>() {
    @Override
    public Subscriber<? super T> call(Subscriber<? super T> subscriber) {
        return new Subscriber<T>() {
            @Override
            public void onCompleted() {
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onCompleted();
                }
            }

            @Override
            public void onError(Throwable e) {
                if (!subscriber.isUnsubscribed()) {
                    try {
                        subscriber.onError(e);
                    } catch (Throwable t) {
                        if (!(t instanceof OnErrorNotImplementedException)) {
                            throw t;
                        }
                    }
                }
            }

            @Override
            public void onNext(T t) {
                if (!isUnsubscribed()) {
                    subscriber.onNext(t);
                }
            }
        };
    }
});

The problem with this if observeOn() is called later then this will be asynchronous and obviously my exception handling here will not work.

Is there way to achieve this. I wish there would be a subscribe() method which does not throw OnErrorNotImplementedException in onError.

Answer

FireZenk picture FireZenk · May 30, 2016

Here is another possible solution, you can define the onNext and a Throwable (also you cannot loose the lambda syntax):

.subscribe(t -> doSomething(t), e -> showError(e));