Using a ReturnValueHandler to adapt RxJava Observables to Deferredresult in a SpringBoot micro service

If you look at my previous blog posts related to RxJava Spring Boot landscape you may notice that all the subscriptions to the RxJava Observables are made in each and every controller method and controller method is responsible for the transformation between RxJava Observables and Spring aware DeferredResults. This is pretty one to one mapping that you can do between RxJava and Spring. You can go further and generalize this behaviour. This will eliminate lots of boilerplate code in your application and make your code much simple, composable and readable. Also this brings a good software engineering practice called generalization and reuse into our code. Take a look at the following controller code before adding the return value handler. 

We can use a simple ReturnValueHandler that calls an adapter that will adapt Observables to DeferredResults. By registering this value handler with Spring, all the methods that return an Observable will be reworked into returning a DeferredResult. When you use DeferredResults as a return type you are instructing Spring that your REST service is asynchronous. By doing this you get the benefit of asynchronous programming by having more efficient usage of your resources.  Our first step is to write code for the return value handler which is given below.

 Next this value handler should be registered with Spring. For that we need to have following configuration class in place.

Then we can get back to our Controller or Resource classes and remove all the boilerplate code used to subscribe to the Observables and adapt them to DeferredResults. Now our controller classes merely return RxJava Observables. The simplified code is given below.

See how simple, composable and readable this code is compared to the previous incarnation of our Resource class. You may find the source code of the project here.

Well, today we kept a step beyond the previous incarnation of our RxJava spring boot microservices by enhancing it to use a return value handler to adapt RxJava Observables into DeferedResults asynchronously. We generalized asynchronous response handling code while making it more simple, composable and readable. I hope you may use these components somewhere down the line in your projects. That does it for another blog post and I’ll see you in my next article.


Popular posts from this blog

WSO2 ESB Worker Manager Cluster without a Load Balancer

XML to XML transformation via Smooks Mediator in WSO2 ESB

JMS 2.0 Support in WSO2 ESB