如何从 Mono<Boolean> 类型字段中提取值?

How do you extract a value from a Mono<Boolean> type field?

我是 java 反应式的新手,我正在做我认为很容易做的事情。

我的目的是评估 return 是 Mono<Boolean> 类型值的方法调用的结果,然后根据该结果确定行动方案。在下面的示例中,如果 fieldAExists 为真,我想 运行 在 addFieldA 方法的后半部分执行更新的代码。

如何从 Mono<Boolean> 类型值中提取布尔值?是否可以从 Mono<Boolean> 字段中提取值?我尝试使用 subscribe() 但无法将其设为 return 我评估的值。

两个反应式语句可以组合成一个语句吗?不胜感激。

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);
        }
    });
}