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

问题描述 投票:1回答:1

我是java reactive的新手,我正在为我认为很容易做的事情绞尽脑汁。

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

如何从一个布尔值中提取一个 Mono<Boolean> 类型值?是否可以从 Mono<Boolean> 字段?我试着用subscribe()工作,但无法让它返回一个值给我评估。

能否将两个反应式语句合并成一个语句? 任何你能提供的方向都是感激的。

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

java spring rx-java reactive
1个回答
1
投票

您可以将它们与 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);
        }
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.