我正在寻找 rxjava2 中推荐的做法是什么来处理一个可流动导致条件行为的情况。
更具体地说,我有一个 Maybe<String>
我想为此更新 String
在数据库上,如果 String
存在,或者,如果它不存在,我想创建一个新的 String
并将其保存在数据库中。
我想到了以下内容,但显然这不是我要找的:
Maybe<String> source = Maybe.just(new String("foo")); //oversimplified source
source.switchIfEmpty(Maybe.just(new String("bar"))).subscribe(result ->
System.out.println("save to database "+result));
source.subscribe(result -> System.out.println("update result "+result));
上面显然产生
save to database foo
update result foo
我也尝试了下面给出预期结果的方法,但仍然觉得它......很奇怪。
Maybe<String> source = Maybe.just(new String("foo")); //oversimplified source
source.switchIfEmpty(Maybe.just(new String("bar")).doOnSuccess(result ->
System.out.println("save to database "+result))).subscribe();
source.doOnSuccess(result -> System.out.println("update result "+result)).subscribe();
当结果存在和不存在时,我如何才能采取行动?应该如何在 rxjava2 中处理该用例?
更新01
我尝试了下面的方法,它看起来比上面的方法更干净。注意肯定是推荐rxjava2的做法不过...
Maybe.just(new String("foo"))
.map(value -> Optional.of(value))
.defaultIfEmpty(Optional.empty())
.subscribe(result -> {
if(result.isPresent()) {
System.out.println("update result "+result);
}
else {
System.out.println("save to database "+"bar");
}
});
最佳答案
你有 isEmpty() 运算符,它会在 Maybe 源是否为空时返回 boolean 值,然后你可以对其进行平面映射并根据该 boolean 值编写 if else 语句
关于java - rxjava2 - if else on Maybe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47096251/