我是 java reactive 的新手,正在做我认为很容易做的事情。
我的目的是评估返回 Mono<Boolean>
的方法调用的结果输入值,然后根据该结果确定行动方案。在下面的示例中,如果 fieldAExists
是的,我想在 addFieldA 方法的后半部分运行执行更新的代码。
如何从 Mono<Boolean>
中提取 boolean 值类型值?是否可以从 Mono<Boolean>
中提取值 field ?我尝试使用 subscribe() 但无法让它返回一个值给我评估。
可以将两个 react 语句组合成一个语句吗?不胜感激。
public Mono<Boolean> addFieldA(Email email, String fieldA) {
Mono<Boolean> fieldAExists = checkFieldAExistence(email);
// if fieldAExists is true, call the below.
return reactiveMongoTemplate.updateMulti(query(where("customer.email.address").is(email.address())),
new Update().set("customer.publicId", fieldA), Account.class, accountCollection).map(result -> {
if (result.wasAcknowledged()) {
return true;
} else {
throw new IllegalArgumentException(
"Error adding fieldA value to customer with email address " + email.address());
}
});
}
public Mono<Boolean> checkFieldAExistence(Email email) {
return reactiveMongoTemplate
.findOne(query(where("customer.email.address").is(email.address()).and("customer.fieldA").ne(null)),
Account.class, accountCollection)
.map(found -> true).switchIfEmpty(Mono.just(false));
}
最佳答案
您可以将它们与 flatMap
结合使用像这样:
public Mono<Boolean> addFieldA(Email email, String fieldA) {
return checkFieldAExistence(email).flatMap(fieldAExists -> {
if (fieldAExists) {
return reactiveMongoTemplate.updateMulti(query(where("customer.email.address").is(email.address())),
new Update().set("customer.publicId", fieldA), Account.class, accountCollection).map(result -> {
if (result.wasAcknowledged()) {
return true;
} else {
throw new IllegalArgumentException(
"Error adding fieldA value to customer with email address " + email.address());
}
});
} else {
return Mono.just(false);
}
});
}
关于java - 如何从 Mono<Boolean> 类型字段中提取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62307982/