Search code examples
javaspringspring-bootreactive-programmingspring-webflux

void vs Mono<Void> in Spring webflux


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!"));
      }
    }