Reputation: 24689
I would like to know what is the appropriate way obtaining an object from a Mono
(or Flux
) to pass onto a non-reactive method such as a JpaRepository
.
Here is the way I did it:
@Service
public class ReactiveAccountService {
//AccountService's methods take non-mono/non-flux objects as arguments
private AccountService accountService;
public ReactiveAccountService(AccountService accountService) {
this.accountService = accountService;
}
public Mono<Void> signUp(Mono<Account> accountMono) {
//Account is a Jpa entity
accountMono.subscribe(account -> accountService.signUp(account));
return Mono.empty();
}
}
How can this be improved? Can someone please advise?
Upvotes: 0
Views: 1176
Reputation: 121482
The better way to do that is like this:
public Mono<Void> signUp(Mono<Account> accountMono) {
//Account is a Jpa entity
return accountMono.flatMap(account -> {
accountService.signUp(account);
return Mono.empty();
});
}
This way you follow Reactive Streams requirements and don't bother the execution flow with your blocking code. Plus according the Spring WebFlux requirements you don't subscribe in your own code, but deffer everything to the container which is an initiator of that Mono<Account>
. The actual execution will happen, when there is enough resources in the Web (Reactive) container to subscribe to the returned Mono
.
Upvotes: 1