6

I'm trying to learn how to use MongoDB reactive repositories using spring-boot 2.0.0.M2, but I fear that I'm not doing things as intended.

This is one of my methods, which tries to find a User by their email. But if there is none, the method should throw an exception.

@Override
public Mono<User> findByEmail(String email) {
    User user = repository.findByEmail(email).block();
    if(user == null) {
        throw new NotFoundException("No user account was found with email: " + email);
    }
    return Mono.just(user);
}

The repository extends ReactiveCrudRepository<User, String>, but I fear that by using .block() I'm preventing this method from being reactive. I'm new to reactive programming, and I'm having a hard time to find good documentation on it. Can someone please point me in the right direction?

1 Answer 1

23

Reactive programming requires a flow that is end-to-end reactive to gain the actual benefits that come from a reactive programming model. Calling .block() within the flow enforces synchronization and is considered an anti-pattern.

For your code, just propagate the Mono you obtain from ReactiveCrudRepository and apply the switchIfEmpty operator to emit an error signal if the Mono terminates without emitting a value. null values are not allowed in the Reactive Streams spec (the spec that Project Reactor is based on). If a result yields no value, then the Publisher does not emit a value.

@Override
public Mono<User> findByEmail(String email) {

    Mono<User> fallback = Mono.error(new NotFoundException("No user account was found with email: " + email));
    return repository.findByEmail(email).switchIfEmpty(fallback);
}

See also:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I had totally missed the switchIfEmpty(...) method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.