如何使用 RxJava 1.x 向调用者抛出异常,而不是处理它?

How to throw an exception up to the caller, rather than handle it, using RxJava 1.x?

我有一个使用 RxJava 的方法调用 jackson 对象映射器将 json 对象反序列化为 java 对象 (POJO)。 readValue 方法抛出一个 IOException,必须处理或抛给我的方法的调用者。我不应该在这里处理它,而是让我的调用者处理它。我如何在 RxJava 中执行此操作?通常它只需要将 throws IOException 添加到我的方法签名中。

这是我的代码:

public Observable<T> findByIdAsync(String id) throws IOException {
    return datasource
            .getBucket()
            .async()
            .get(String.valueOf(id), RawJsonDocument.class)
            .map(json -> objectMapper.readValue(json.content(), getType()));
}

objectMapper.readValue(json.content(), getType()) 抛出 IOException 所以它必须被捕获或抛出。

只需使用 fromCallable:

将您的 readValue 方法包装到 Observable

Returns an Observable that, when an observer subscribes to it, invokes a function you specify and then emits the value returned from that function.

.flatMap(json -> Observable.fromCallable(() -> 
                      objectMapper.readValue(json.content(), getType())))

Callable 中抛出的任何 Exception 将中断流,并且将触发 Subscriber's onError 回调(如果未在流中的某处处理)。