Sunday, July 23, 2017

Reactor: Reactive Programming Java 8

One of the more interesting features in the upcoming release of Java 9 is the support for Reactive Programming in Java. At a high-level Reactive programming deals with asynchronous data streams. Reactive streams provides a standard for asynchronous stream processing. Java 9 supports Reactive programming implementing the Reactive Streams specification through the Flow API. But before the release of Java 9, there are ways to implement Reactive programming in Java 8. Reactor and RxJava are a couple of APIs to implement Reactive streams in Java 8. Reactor is used internally by the Spring Framework to it's own Reactive support in version 5. In this post, we will look into Reactor library.

Reactive Streams

Reactive Streams API has two high-level interfaces, Publisher and Subscriber. A Publisher is the source of events, while a Subscriber is the destination for those events. A Subscriber subscribes to a Publisher. When a Subscriber subscribes to a Pulisher, the Publisher invokes the onSubscribe() method on the Subscriber. When the Subscriber is ready to start handling events, it signals this via a request to that Subscription using the request() method. Upon receiving this signal, the Publisher begins to invoke onNext() for each event. This continues until either completion of the stream onComplete() or an error onError(Throwable).

Reactor

While Reactive Streams defines the high-level interfaces, the actual implementation is not provided. The Reactor API provides implementations for these interfaces. The main Publishers provided by Reactor API are Flux and Mono. Flux is a publisher that can publish an unlimited number of events, while Mono can publish at most one event.

Flux

There are many ways to create a Flux. Flux provides a few static methods to create instances.

Mono

Subscriber

For this example, we will write a simple subscriber which prints the elements. To handle backpressure, this subscriber will read only one element. After processing each element, we will request one more element.