什么是 RxJava 相当于 orElse [英] What is RxJava equivalent of orElse

查看:34
本文介绍了什么是 RxJava 相当于 orElse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在其他语言的流/函数领域有一个常见的操作,那就是 orElse().它就像一个 if,当当前链没有得到任何结果时,它会更改为备用链.在具有 Maybe 类型的语言中,它基本上会延续 Some 类型的链,或者在 None 类型上更改为 orElse.

There is one common operation in stream/functional land in other languages, that's orElse(). It serves like an if, where when the current chain didn't get any result, it changes to the alternate one. In a language with Maybe types it'd basically continue the chain for a Some type or change to the orElse on a None type.

理想情况:

Observable.just(false)
          .filter(value -> { return value; })
          .map(value -> { return 1; })
          .orElse(Observable.just(0));

Observable.<Boolean>error(new IllegalStateException("Just playing"))
          .filter(value -> { return value; })
          .map(value -> { return 1; })
          .orElse(Observable.just(0));

目前可以使用 concat 和 takeFirst 进行复制,但它在语义上并不相同,并且没有正确涵盖错误处理.

It can be currently reproduced using concat and takeFirst, but it's just not semantically the same, and doesn't cover error handling properly.

Observable.concat(Observable.just(false)
                            .filter(value -> { return value; })
                            .map(value -> { return 1; }), 
                  Observable.just(0))
          .takeFirst();

推荐答案

看起来他们有这个,但命名不同:defaultIfEmpty 或 switchIfEmpty.

It looks like they have that, but with different naming: defaultIfEmpty or switchIfEmpty.

Observable.just(false)
        .filter(value -> value)
        .map(value -> 1)
        .defaultIfEmpty(0)
        .subscribe(val -> {
            // val == 0
        });

Observable.just(false)
        .filter(value -> value)
        .map(value -> 1)
        .switchIfEmpty(Observable.just(0))
        .subscribe(val -> {
            // val == 0
        });

// Error thrown from the first observable
Observable.<Boolean>error(new IllegalStateException("Crash!"))
        .filter(value -> value)
        .map(value -> 1)
        .switchIfEmpty(Observable.<Integer>error(new IllegalStateException("Boom!")))
        .subscribe(val -> {
            // never reached
        }, error -> {
            // error.getMessage() == "Crash!"
        });

// Error thrown from the second observable
Observable.just(false)
        .filter(value -> value)
        .map(value -> 1)
        .switchIfEmpty(Observable.<Integer>error(new IllegalStateException("Boom!")))
        .subscribe(val -> {
            // never reached
        }, error -> {
            // error.getMessage() == "Boom!"
        });

这篇关于什么是 RxJava 相当于 orElse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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