【问题标题】:Java Observable to throw error if it occurs如果发生错误,Java Observable 会抛出错误
【发布时间】:2017-10-17 16:33:01
【问题描述】:

有没有办法让 Observable 只抛出一个发生在像 flatMap() 这样的函数中的异常?

在Java中,在普通函数上,你可以指定它可能会抛出异常:

public void dangerousFunction() throws IOException {}

在像flatMap() 这样的Observable 函数中,我似乎找不到类似的语法。我可以像这样使用try/catch:

myObservable.flatMap(() -> {
    try {
        return dangerousFunction();
    } catch (IOException e) {
        return Observable.error(e);
    }
});

有没有更简洁的方法来编写它?如果我有很多地图和/或Observables,那么最终会有很多try/catch 块把我的代码弄得乱七八糟。

【问题讨论】:

标签: java rx-java observable


【解决方案1】:

在 RxJava map() 方法中处理异常的标准方法是通过 catch-and-throw 传播异常。例如:

.map(b -> {
   try {
       ...
   } catch (IOException ex) {
       // manual catch and throw
       throw new RuntimeException(ex);

       // or catch-and-throw using a built-in helper
       throw Exceptions.propagate(e);
   }
})

当在多个 map() 调用中重复时,这可能会变得非常冗长,因此您可以定义一个帮助器来包装此行为,例如

observable.map(RxMapWrapper.wrapAndThrow(new RxMapWrapper.Func1Wrapper<A, B>() {
        @Override
        public B call(A document) throws Exception {
            // your map logic here ...
        }
    }))

public class RxMapWrapper {
    public static <T, R> Func1<T, R> wrapAndThrow(Func1Wrapper<T, R> caughtFunction) {
        return t -> {
            try {
                return caughtFunction.call(t);
            } catch (Exception e) {
                throw Exceptions.propagate(e);
            }
        };
    }

    public interface Func1Wrapper<T, R> extends Function {
        R call(T t) throws Exception;
    }
}

【讨论】:

    【解决方案2】:

    如果您只想在 catch 块中返回 Observable.error(e),则根本不需要 try/catch。异常会转到下游,.subscribe(,throwable) 无论如何都会捕获它。

    如果您想在发生错误时返回一些其他/默认对象,请尝试以下运算符:onErrorReturnItem、onErrorResumeNext、onErrorReturn。这样会更干净。

    其他选项是在你的方法中实现这个onErrorReturnItem 机制,而不是抛出异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 2021-12-27
      • 2016-05-02
      • 1970-01-01
      • 2018-01-21
      • 2016-06-13
      • 1970-01-01
      相关资源
      最近更新 更多