void vs Mono<Void> in Spring webflux

Issue

I recently started working on Spring Webflux application using reactive streams. I have 2 questions.

  1. What is the difference between void and Mono<Void>

  2. I have a usecase like the following where I think could be improved using void or Mono<Void>

     @Service
     public class ABCService {  
       public Mono<String> getGreeting(String name) {
         Mono.just(NameValidator.validate(name))
              .map(isValid -> "Hello, "+name+". Welcome!");
       }
    
     }
    
     public class NameValidator {
    
       public static boolean validate(String name) {
         if(StringUtils.isEmpty(name)) {throw new RuntimeException("Invalid name");}
         return true;
    
      }
    
     }
    

I dont actually need the validate() method to have a boolean return type. It could be void/Mono<Void> instead. I only return true to performing chaining in the ABCService. Can someone explain how to do the same using void and Mono<Void>

Solution

If you return Mono you can’t use map(). I mean you can use it, but since Mono<Void> will never emit a value but only a completion signal, your map() will never take effect. You would need to replace it with then():

@Service
public class ABCService {  
  public Mono<String> getGreeting(String name) {
      NameValidator.validate(name)
         .then(Mono.just("Hello, "+name+". Welcome!"));
  }
}

Answered By – João Dias

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published