Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return Flux of objects after calling a mono boolean method

I have a validator method that returns a Mono<Boolean>.
The validation is happening as expected and returns bad request exception in case of invalid id1 or id2.

public static Mono<Boolean> validate(String id1, String id2) {
   //some condition to check id1 & id2.
   // either return Mono.just(false)/mono.just(true)
   // or return Mono.error(new BadRequestException("")); 
}

However, the control is going to the next line instead of returning from the execution.
Here is the method where the validator method is referred:

public Flux<FacilitiesResponse> validateAndGetFacilityResponse(String id1, String id2) {
    validate(id1,id2);
    return facilityService.getFacilityResponse(id1,id2);  
 }

The validator method returns Mono<Boolean>, but the method returns Flux<FacilitiesResponse>. How to re-write this whole method in reactive way such that it returns Flux< FacilitiesResponse> ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried something like below:

return validate(id1,id2)
       .filter(valid -> valid)
       .map(valid -> facilityService.getFacilityResponse(id1,id2)) 

but it gives me Mono<Flux< FacilitiesResponse>> instead.

Unfortunately, I cannot change the return type of facilityService.getFacilityResponse(id1,id2).

>Solution :

In your first example nothing happens with validate(id1,id2); because no one subscribes to it. You should build your reactive chain from the start to the end.

To return Flux after the successful validation you should use flatMapMany()

return validate(id1,id2)
        .filter(valid -> valid)
        .flatMapMany(__ -> facilityService.getFacilityResponse(id1,id2));

From flatMapMany() docs:

 * Transform the item emitted by this {@link Mono} into a Publisher, then forward  * its emissions into the returned {@link Flux}.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading