Just to quickly recap, my objective was to develop a reactive service which takes in a request which looks like this:
1 2 3 4 5 6 | { "id" : 1 , "delay_by" : 2000 , "payload" : "Hello" , "throw_exception" : false } |
and returns a response along these lines:
1 2 3 4 5 | { "id" : "1" , "received" : "Hello" , "payload" : "Response Message" } |
I had demonstrated this in two ways that the upcoming Spring's reactive model supports, using the Reactor-Core Flux type as a return type and using Rx-java Observable type
However the catch with these types is that the response would look something like this:
1 | [{ "id" : "1" , "received" : "Hello" , "payload" : "From RxJavaService" }] |
Essentially an array, and the reason is obvious - Flux and Observable represent zero or more asynchronous emissions and so Spring Reactive Web framework has to represent such a result as an array.
The fix to return the expected json is to essentially return a type which represents 1 value - such a type is the Mono in Reactor-Core OR a Single in Rx-java. Both these types are as capable as their multi-valued counterparts in providing functions which combine, transform their elements.
So with this change the controller signature with Mono looks like this:
1 2 3 4 | @RequestMapping (path = "/handleMessageReactor" , method = RequestMethod.POST) public Mono<MessageAcknowledgement> handleMessage( @RequestBody Message message) { return this .aService.handleMessageMono(message); } |
and with Single like this:
1 2 3 4 | @RequestMapping (path = "/handleMessageRxJava" , method = RequestMethod.POST) public Single<MessageAcknowledgement> handleMessage( @RequestBody Message message) { return this .aService.handleMessageSingle(message); } |
I have the sample code available in my github repo
No comments:
Post a Comment