如何返回一个RxJava Observable,保证不会抛出OnErrorNotImplementedException?

时间:2015-09-02 09:09:13

标签: java rx-java

我想在我的应用程序中创建一个模式,其中返回的所有Observable<T>个对象都有一些默认的错误处理,这意味着订阅者可以使用.subscribe(onNext)重载而不用担心应用程序崩溃。 (通常你必须使用.subscribe(onNext, onError))。有没有办法实现这个?

我尝试使用onErrorReturndoOnErroronErrorResumeNext附加到Observable,但没有任何一个帮助我的情况。也许我做错了,但如果Observable中发生错误,我仍然会得到rx.exceptions.OnErrorNotImplementedException

编辑1:这是一个发出错误的Observable的例子,我想在某个中间层处理它:

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

编辑2:我已尝试使用此代码代表消费者处理错误,但我仍然得到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)
);

1 个答案:

答案 0 :(得分:12)

这将有效 - 关键是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));