有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我是java反应式的新手,我认为这是一件非常容易的事情

我的目的是评估返回Mono<Boolean>类型值的方法调用的结果,然后根据该结果确定操作过程。在下面的示例中,如果fieldAExists为true,我想运行在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));
}


共 (1) 个答案

  1. # 1 楼答案

    您可以将它们与^{}组合,如下所示:

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