告诉我如何使用反应式中的条件。

我有简单的DTO SignInRequest和signIn方法。

public class SignInRequest {

  private String userName;
  private String password;
}

public Mono<SignInResponse> signIn(SignInRequest signInRequest) {
    boolean isValid = StringUtils.isEmailValid(signInRequest.getUserName());
    return userService.findByEmail(signInRequest.getUserName())
        .switchIfEmpty(Mono.error(new NotFoundException("User not found [email: " + signInRequest.getEmail() + "]")))
        .filter(user -> passwordService.validatePassword(user.getPassword(), signInRequest.getPassword()))
        .switchIfEmpty(Mono.error(new BadRequestException("Wrong email or password")))
        .flatMap(this::generateTokens);
}


如何正确实现以下逻辑。

如果isValid == true,则调用findByEmail方法。否则,请调用findByUsername

最佳答案

我个人认为,最易读的实现方式如下:

public Mono<SignInResponse> signIn(SignInRequest signInRequest) {
    return Mono
            .fromSupplier(() -> StringUtils.isEmailValid(signInRequest.getUserName()))
            .flatMap(isValid ->
                    isValid ? userService.findByEmail(signInRequest.getUserName())
                            : userService.findByUsername(signInRequest.getUserName())
            )
            .switchIfEmpty(Mono.error(new BadRequestException("Wrong email or password")))
            .flatMap(this::generateTokens);
}

10-08 17:36