Introduce about Project Reactor

In the previous tutorial, I introduced to you all about Reactive Streams in Java which implements Reactive Streams specification. In this tutorial, I will introduce you all one more library that also implements the Reactive Streams specification: it is Project Reactor. How is it in detail? Just continue to read this tutorial.

First, as with any tutorial, I will also create a Maven project as an example:

Introduce about Project Reactor To work with Project Reactor, we need to add its dependency:

Because of the Reactive Streams specification, we also have Publisher, Subscriber, and Subscription concepts in Project Reactor, but with different names.

In Project Reactor, we have two objects that act as Publisher:

  • One is the Flux object: This object can publish from 0 to N items.
  • Second is the Mono object: This object can only publish 1 item or no item.

The difference between these two objects is: if your code returns a Mono object then we can know that this object can only publish up to one item, and for a Flux object we have to code to our application that can handle up to N items. From there, we have a way to develop our application properly.

For Subscriber, we can use an abstract class called BaseSubscriber that implements Subscriber. This class defines predefined methods, like hookOnSubscribe(), hookOnNext(), hookOnComplete(), hookOnError(), hookOnCancel(), and hookFinally(), to help us can develop the Subscriber part of the Reactive Streams application.

OK, now let’s try an example.

First, we will define an object to extend BaseSubscriber abstract class to implement the Subscriber part.

Its object is as follows:

In this Consumer object, as soon as subscribing to Publisher, it will request to retrieve the first item. And every time the Publisher publishes new data, it also requests to retrieve that data.

Next, I will define a Publisher using the Flux object to publish the data.

Flux has many static methods for creating data such as just(), fromArray(), fromIterable(), … In this tutorial, I just use the simple as follows:

The last step is: subscribe our Consumer object to Publisher.

The entire code is as follows:

Result:

Introduce about Project Reactor

Add Comment