Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring-Reactive Samples: Mono and Single

DZone's Guide to

Spring-Reactive Samples: Mono and Single

Join us as we dive into more exploration into Spring's native support for reactive programming.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

This is just a little bit of a learning from my previous post, where I had tried out Spring's native support for reactive programming.

Just to quickly recap, my objective was to develop a reactive service that takes in a request that looks like this:

{
    "id":1,
    "delay_by": 2000,
    "payload": "Hello",
    "throw_exception": false
}


And returns a response along these lines:

{
    "id": "1",
    "received": "Hello",
    "payload": "Response Message"
}


I had demonstrated this in two ways that the upcoming Spring's reactive model supports — using the Rector-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:

[{"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 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 and transform their elements.

So with this change, the controller signature with Mono looks like this:

@RequestMapping(path = "/handleMessageReactor", method = RequestMethod.POST)
public Mono<MessageAcknowledgement> handleMessage(@RequestBody Message message) {
    return this.aService.handleMessageMono(message);
}


And with Single like this:

@RequestMapping(path = "/handleMessageRxJava", method = RequestMethod.POST)
public Single<MessageAcknowledgement> handleMessage(@RequestBody Message message) {
    return this.aService.handleMessageSingle(message);
}


I have the sample code in my GitHub repo.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,spring ,reactive programming ,rx java

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}