Search code examples
javaspring-bootreactive-programming

How to use Mono<Boolean> in if else conditional statement?


I am using Flux<Document> in reactive, so as to make my Rest Service reactive. I am returning ResponseEntity<Flux<Document>> as response to my rest service. Right now my service is always returning HttpStatus.ok(), but I want to enhance it to return HttpStatus.noContent() in case of no content is found. To achieve this am trying to check the size of Flux. I figured out that this can be achieved either by .count() or .hasElements().

IF I consider .hasElements() then it returns Mono<Boolean>. I am trying to understand as a newbie that how can I use this in making decisions between HttpStatus.ok() and HttpStatus.noContent().

Also is this the right way to use conditional statements in reactive or is there any other way to achieve it.

Request you to please help.


Solution

  • So here is what I did to accomplish the above ask:

    final Flux<Document> returnDoc = <Reference of what I received from the Service layer>;
    
    return returnDoc.hasElements()
                    .map(isNotEmpty -> {
                        if (isNotEmpty) 
                            return ResponseEntity.ok().body(returnDoc);
                        else {
                            return ResponseEntity.noContent().build();
                        }
                    });
    

    This worked for me. Let me know if there is any other solution which is better.