Method call after returning Mono<Void>

kostepanych picture kostepanych · Jul 25, 2018 · Viewed 21.2k times · Source

I want to call the method when previous returned Mono<Void>:

 @Override
 public Mono<Void> sendEmail(EmailDto emailDto) {
 return mailReactiveClient.sendEmail(message ->
     createMessage(emailDto, emailDto.getBody(), message))
       .doOnNext(saveNotificationLog(emailDto)); //it's not work
}

  private void saveNotificationLog(EmailDto emailDto) {
    notificationLogReactiveRepository.save(NotificationLog.builder()
       ...
      .build());
  }

Method sendEmailreturns Mono<Void>.

So how to call saveNotificationLog?

UPD: Tring to make my question simplier:

 @Override
 public Mono<Void> sendEmail(EmailDto emailDto) {
 return mailReactiveClient.sendEmail(message ->
     createMessage(emailDto, emailDto.getBody(), message))
       .doOnNext(System.out.print("Hello world!"); 
}

How to call doOnNextor similar method after sendEmail return Mono<Void>?

Answer

wargre picture wargre · Jul 25, 2018

The Mono will not emit data, so doOnNext will not be triggered. You should use the doOnSuccess instead.

Also, your Mono need to be consumed. Without the code, we don't know if it is or not.

Some example here: I added subscribe() to consume the mono. Depending on the use of your Mono, you will have to do or not the same thing.

This print nothing:

Mono<String> m=Mono.just("test");
Mono<Void> v=m.then();
v.doOnNext(x->System.out.println("OK")).subscribe();

This print "OK":

Mono<String> m=Mono.just("test");
Mono<Void> v=m.then();
v.doOnSuccess(x->System.out.println("OK")).subscribe();