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 - Reactor StepVerifier.withVirtualTime 无限期阻塞

java - 在 Chrome 和 Postman 中调试来自 Spring 的服务器发送的事件流

java - Spring Boot 2.2.0 不推荐使用syncBody

java - 将 ArrayList 的每个元素添加到另一个 ArrayList 的每个元素

java - Spring 安全: remember-me cookie is created in the browser but password is not saving

java - Android:Java 中的 Hashmap 或 Sequence

spring-webflux - 如果单声道为空,怎么会出现异常?

java - Project Reactor 的 flatMap 中关于线程的混淆

java - 如何在 Spring Sleuth 中的响应式(Reactive)调用链中命名 Span

java - 与 (if) 条件无关的错误 : syntax error on token invalid character, 删除此 token