Search code examples
spring-webfluxreactor

How can I use Mono<Boolean> as condition to call second method


I'm trying to make a call to one service after checking a condition from another service in an iterative way, like so:

if (productService.isProductNotExcluded(product)){
    List<Properties> properties = propertiesService.getProductDetailProperties(product)
...
}

But since isProductExcluded is returning Mono<Boolean> I'm using this approach, which seems really odd:

Flux<Properties> properties = productService.isProductNotExcluded(productId)
     .filter(notExcluded -> notExcluded)
     .map(ok-> propertiesService.getProductDetailProperties(product))
     ...

Which is the correct way to deal with this kind of situation?


Solution

  • For a predicate which returns a Mono<Boolean>, you can also use filterWhen which takes a publisher as a predicate. Something like this:

    Flux<Properties> properties = Mono.just(productId)
    .filterWhen(prodId -> productService.isProductNotExcluded(prodId))
    .map(validProductId -> propertiesService.getProductDetailProperties(validProductId));