[英]RxJava, execute observable only if first was empty
I want to insert a new user into my database only if a user with the same email does not exist. 仅当具有相同电子邮件的用户不存在时,我才想将新用户插入到我的数据库中。
Therefor I have two Observables: The first one emits a user with a specific email or completes without emitting anything. 因此,我有两个Observable:第一个使用特定电子邮件发出用户或完成而不发出任何内容。 The second Observable inserts a new user and returns an Object of this newly created user. 第二个Observable插入一个新用户并返回这个新创建的用户的Object。
My problem is, that I don't want the user emmitted by the first Observable (if existent) is transported to the Subscriber. 我的问题是,我不希望第一个Observable(如果存在)所传递的用户被传输到订阅服务器。 Rather I would like to map it to null). 相反,我想将它映射到null)。
Observable<UserViewModel> observable =
checkAndReturnExistingUserObservable
.map(existingUser -> null)
.firstOrDefault(
insertAndReturnNewUserObservable
.map(insertedUser -> mMapper.map(insertedUser)
)
This was the last thing I tried, but it says "cyclic inference" at the second map operator. 这是我尝试的最后一件事,但它在第二个地图操作员处说“循环推理”。
To summarize. 总结一下。 I want to perform a second Observable only if the first completed empty but if not I don't want to return the Data emmitted by first rather I want to return null. 我想只在第一个完成空的情况下执行第二个Observable,但如果不是我不想首先返回数据,而不想返回null。
Any help is really appreciated. 任何帮助都非常感谢。
There is the switchIfEmpty
operator for this kind of operation: switchIfEmpty
操作有switchIfEmpty
运算符:
checkAndReturnExistingUserObservable
.switchIfEmpty(insertAndReturnNewUserObservable)
Edit 编辑
If you don't need an existing user, there was a flatMap-based answer that turned the first check into a boolean value and dispatched based on its value: 如果您不需要现有用户,则会有一个基于flatMap的答案,它将第一个检查转换为布尔值,并根据其值进行调度:
checkAndReturnExistingUserObservable
.map(v -> true).firstOrDefault(false)
.flatMap(exists -> exists ? Observable.empty() : insertAndReturnNewUserObservable);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.