Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
977 views
in Technique[技术] by (71.8m points)

java - Best practices for Conditional Flow with Project Reactor

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 :

Business Flow Chart

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?

question from:https://stackoverflow.com/questions/65924135/best-practices-for-conditional-flow-with-project-reactor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...