Method call after returning Mono<Void>

kostepanych :

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

Brian Clozel :

doOnNext, and in general all doOn* reactor methods are side-effect methods. You're not supposed to call them to do I/O work or chain operations, but rather log things and not do anything that would affect the state of the application.

In your code sample, notificationLogReactiveRepository.save returns Mono<Void>. The saveNotificationLog returns void and does not subscribe to the publisher returned by notificationLogReactiveRepository.save. This means the notification will not be saved, because nothing happens until you subscribe.

In this case, it seems you're trying to chain operations - then operators are just made for that. Your code should look like this:

@Override
public Mono<Void> sendEmail(EmailDto emailDto) {
    return mailReactiveClient.sendEmail(message ->
        createMessage(emailDto, emailDto.getBody(), message))
           .then(saveNotificationLog(emailDto));
}

private Mono<Void> saveNotificationLog(EmailDto emailDto) {
    return notificationLogReactiveRepository.save(NotificationLog.builder()
        ...
        .build());
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72207&siteId=1