Reputation: 21
I am working with spring webflux and project reactor building an API with 2 layers: controller and service. All the 3 endpoints that my API have send and return a request/response wrapped with Mono. In the service layer I have two classes: the first one calls several webclients with Mono responses and the second one is the class integration for those calls. I have been struggling with building "pipeline" of Mono calls because the business flow dictate that I need to call webclient 1, do some validation, use its response and call webclient 2, perform validation call webclient 3 if passes otherwhise webclient 4 and so on... I have tried with flatmap but its not natural for me create a conditional flow with Mono like this :
As you can see on the diagram i'ts not a easy way for me to implement the conditional flow of reactive web client calls. There is a best practice to do this whitout calling a nested calls of flatmaps, and maps and with good readability of my code?
Upvotes: 1
Views: 1755
Reputation: 71
You may place conditional statements to flatMap
and use switchIfEmpty to return other publisher. A short example:
myService.executeWc1() // returns Mono
.flatMap(result -> myService.executeWc2(result))
.flatMap(result -> validator.validate(result))
.handle((result, sink) -> {
if (result) { // validation is passed
sink.success(true);
}
sink.success();
})
.flatMap(result -> myService.doSomeWork()
.flatMap(r -> myService.executeWc3())
.flatMap(r -> myService.doSomeWorkAgain())
.flatMap(r -> myService.executeWc4()))
.switchIfEmpty(myService.executeWc4())
and so on...
Upvotes: 2