简体   繁体   中英

How can I return an RxJava Observable which is guaranteed not to throw OnErrorNotImplementedException?

I want to create a pattern in my application where all Observable<T> objects that are returned have some default error handling, meaning that the subscribers may use the .subscribe(onNext) overload without fear of the application crashing. (Normally you'd have to use .subscribe(onNext, onError) ). Is there any way to acheive this?

I've tried attaching to the Observable by using onErrorReturn , doOnError and onErrorResumeNext - without any of them helping my case. Maybe I'm doing it wrong, but I still get rx.exceptions.OnErrorNotImplementedException if an error occurs within the Observable.

Edit 1: This is example of an Observable that emits an error, which I want to handle in some middle layer:

Observable.create(subscriber -> {
    subscriber.onError(new RuntimeException("Somebody set up us the bomb"));
});

Edit 2: I've tried this code to handle the error on behalf of the consumer, but I still get OnErrorNotImplementedException :

// obs is set by the method illustrated in edit 1
obs = obs.onErrorResumeNext(throwable -> {
    System.out.println("This error is handled by onErrorResumeNext");
    return null;
});
obs = obs.doOnError(throwable -> System.out.println("A second attempt at handling it"));
// Consumer code:
obs.subscribe(
    s -> System.out.println("got: " + s)
);

This will work - the key was to return Observable.empty();

private <T> Observable<T> attachErrorHandler(Observable<T> obs) {
    return obs.onErrorResumeNext(throwable -> {
        System.out.println("Handling error by printint to console: " + throwable);
        return Observable.empty();
    });
}

// Use like this:
Observable<String> unsafeObs = getErrorProducingObservable(); 
Observable<String> safeObservable = attachErrorHandler(unsafeObs);
// This call will now never cause OnErrorNotImplementedException
safeObservable.subscribe(s -> System.out.println("Result: " + s));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM