Search code examples
spring-webfluxproject-reactor

Conditional Behavior in project Reactor stack


I need to create a method that gets data from external cache. If a data is found it does some processing otherwise it should do different processing. The method should return Mono

Mono<Void> myMethod() {
   return getDataFromCache()
             .flatMap(data -> processDataFromCache(data))
             .switchIfEmpty(Mono.defer(() -> doSomethingElse()));
}

The issue I'm having is, because processDataFromCache(data) return type is Mono<Void>, the switchIfEmpty part is always executed. Is there a way to do this differently?


Solution

  • If you cannot change the behavior of the processDataFromCache and doSomethingElse then you can connect them with some fake values coming after their successful execution:

    Mono<Void> myMethod() {
       return getDataFromCache()
                 .flatMap(data -> processDataFromCache(data).then("processed"))
                 .switchIfEmpty(Mono.defer(() -> doSomethingElse().then("new")))
                 .then();
    }