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?
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: