我正在寻找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));
Run Code Online (Sandbox Code Playgroud)
以上显然产生了
save to database foo
update result foo
Run Code Online (Sandbox Code Playgroud)
我也试过下面给出了预期的结果,但仍觉得它......很奇怪.
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();
Run Code Online (Sandbox Code Playgroud)
如何在结果存在时以及何时不存在时执行操作?该用例应该如何在rxjava2中处理?
我尝试了以下,它看起来比我上面提到的更清洁.注意确定推荐使用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");
}
});
Run Code Online (Sandbox Code Playgroud)
小智 0
尝试这样的事情。checkDB可以返回 Maybe 或 Single 或任何发出optional包装对象的对象。
checkDB(String)
.flatMap(s -> {
if (s.isPresent()) {
return updateDB(s.get());
} else {
return insertDB("new String");
}
})
Run Code Online (Sandbox Code Playgroud)