rx-java2 flatMap 中的空处理 [英] Null handling in rx-java2 flatMap

查看:49
本文介绍了rx-java2 flatMap 中的空处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档中所述RxJava 2.x 不再接受空值.因此,以下两行都以 onError 调用终止也就不足为奇了:

As explained in the docs RxJava 2.x no longer accepts null values. So it is not surprising that both of the following two lines terminate with onError called:

Observable.fromCallable(() -> null);
Observable.just(1).flatMap(i -> Observable.error(new RuntimeException()));

不清楚的是为什么

Observable.just(1).flatMap(i -> Observable.fromCallable(() -> null))

以成功终止并且不发出任何项目.期望它以与 Observable.error

terminates with success and no items emitted. It seams reasonable to expect for it behave in the same fashion as Observable.error

我可以在rx-java 2.1.2的源代码中看到

I can see in source code of rx-java 2.1.2

 public final <R> Observable<R> flatMap(...) {
    if (this instanceof ScalarCallable) {
        @SuppressWarnings("unchecked")
        T v = ((ScalarCallable<T>)this).call();
        if (v == null) {
            return empty();
        }
        ...
 }

从代码的角度解释了为什么会发生这种情况,但我仍然有两个问题:

which explains why it is happening in terms of code, but I still have two questions:

1) 这是预期行为还是错误?

1) Is this is an intended behavior or a bug?

2) 如果有意,是否有原因?

2) If intended, is there a reason for this?

推荐答案

这是 Observable.fromCallable 的一个错误,将通过 PR 5517.

This is a bug with the Observable.fromCallable and will be fixed with PR 5517.

如果由于某种原因您无法避免在此设置中返回空值,您可以应用 hide() 来解决此错误:

If, for some reason you can't avoid a null return in this setup, you can apply hide() to workaround this bug:

Observable.just(1).flatMap(i -> Observable.fromCallable(() -> null).hide())

或者帮助 RxJava 抛出:

or help RxJava throw:

Observable.just(1)
    .flatMap(i -> Observable.fromCallable(() -> 
         java.util.Objects.requireNonNull(apiReturningNull()))
    )

这篇关于rx-java2 flatMap 中的空处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆