处理RxJava中的已检查异常

时间:2017-07-07 12:51:56

标签: rx-java

我开始掌握RxJava1(现在让我们不介绍RxJava2的原因)。

我的代码如下:

MoviesAPI.findMovieURLsByType("comedy")
.map(s -> {
                    try {
                        return potentialCheckedException(s); //Throws CheckedException
                    } catch (MyExceptionType ex) {
                        return Exceptions.propagate(ex);
                    }
})
.subscribe(new Subscriber<String>() {
                    public void onCompleted() {
                        System.out.println("------Completed!-------");
                    }

                    public void onError(final Throwable e) {
                        System.out.println(e.getMessage());
                    }

                    public void onNext(final String s) {
                        System.out.println(s);
                    }
});

我得到如下编译错误:

Error:(28, 17) java: no suitable method found for subscribe(<anonymous rx.Subscriber<java.lang.String>>)
    method rx.Observable.subscribe(rx.functions.Action1<? super java.io.Serializable>) is not applicable
      (argument mismatch; <anonymous rx.Subscriber<java.lang.String>> cannot be converted to rx.functions.Action1<? super java.io.Serializable>)
    method rx.Observable.subscribe(rx.Observer<? super java.io.Serializable>) is not applicable
      (argument mismatch; <anonymous rx.Subscriber<java.lang.String>> cannot be converted to rx.Observer<? super java.io.Serializable>)
    method rx.Observable.subscribe(rx.Subscriber<? super java.io.Serializable>) is not applicable
      (argument mismatch; <anonymous rx.Subscriber<java.lang.String>> cannot be converted to rx.Subscriber<? super java.io.Serializable>)
    method rx.Observable.<T>subscribe(rx.Subscriber<? super T>,rx.Observable<T>) is not applicable
      (cannot infer type-variable(s) T
        (actual and formal argument lists differ in length))

如果我要删除try-catch块并用potentialCheckedException(s)替换noPotentialCheckedException(s),那么编译错误就会消失。为什么?我错过了什么?使用CheckedException不足以包裹Exceptions.propagate(ex)吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

Exceptions.propagate返回RuntimeExceptionpotentialCheckedException返回String我假设。然后,lambda返回类型推断只能找到Serializable的常见超类型,它与显式类型的String订阅者不兼容。您更可能想要throw Exceptions.propagate(ex)