java - Reactor - 为两个流编写值检查的更好方法

标签 java spring-webflux project-reactor

我的代码中有以下方法。正如您所看到的,它包含嵌套映射,用于检查数据库中是否已存在用户名。我想以更优雅的方式写它,但我不知道如何。有什么建议吗?

   @Override
    public Mono<User> registerUser(User user) {

      return emailExists(user.getEmail())
                .flatMap(emailExists -> {
                    if(emailExists) {
                        return Mono.error(new EmailExistsException(
                                "There is an account with that email address: "
                                        + user.getEmail() ));
                    } else {
                        return usernameExists(user.getUsername())
                                .flatMap(usernameExists -> {
                                    if(usernameExists) {
                                        return Mono.error(new UsernameExistsException(
                                                "There is an account with that username: "
                                                        + user.getUsername() ));
                                    } else {
                                        return userRepository.save(user);
                                    }
                                });
                    }
                })

    }

最佳答案

您可以使用filterWhen,但您需要反转现有检查。这个想法是让用户过滤器不存在时传递该过滤器,从而可以创建:

//start from the user itself
Mono.just(user)
    //check if it exists, and if so fail the filter => empty mono
    .filterWhen(u -> emailExists(u.getEmail()).map(exist -> !exist))
    //on an empty Mono at this point, we know it's a duplicate email
    .switchIfEmpty(Mono.error(new EmailExistsException(
                "There is an account with that email address: " + user.getEmail() )))
    //now check if username exists, and similarly fail the filter
    .filterWhen(u -> userNameExists(u.getUsername()).map(exist -> !exist))
    //if empty at this point we know it's a duplicate username
    .switchIfEmpty(Mono.error(new UsernameExistsException(
                "There is an account with that username: " + user.getUsername() )))
    //otherwise it's not empty and it means that User can be saved
    .flatMap(userRepository::save)

关于java - Reactor - 为两个流编写值检查的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007975/

相关文章:

java - 在一条语句中删除多行

java - 如何在 JSF 中的数据表顶部添加新行?

java - 使用自定义适配器中的变量时遇到问题

java - 如何使用 Spring Boot 单独访问作为 Mono 对象返回的属性

java - 如何将 DynamoDB 与 Project Reactor 结合使用?

java - 作为 if 语句的结果,如何在另一个 react 流中使用一个 react 流

java - 如何让 Flux 的多个订阅者在不同的执行上下文/线程上运行

java - 在Java中为类的参数设置值

java - 如何在Reactor中进行分页?

用于 API 的 Spring webflux 自定义身份验证