Search code examples
androidrx-javarx-java2subscribe

Prevent OnErrorNotImplementedException


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.


Solution

  • here's how we do it at work. Instead of making actions we made an abstract NYTSubscriber which has onError and onCompleted implemented. This way you can use this subscriber and only implement the onNext callback OR you can override onError and onCompleted when necessary

    public abstract class NYTSubscriber<T> extends Subscriber<T> {
    
    @Override
    public void onCompleted() {
    }
    
    @Override
    public void onError(Throwable e) {
    }
    }