Introduce about Project Reactor

In the previous tutorial, I introduced with you all about Reactive Streams in Java which implementing Reactive Streams specification. In this tutorial, I will introduce with you all one more library that also implements the Reactive Streams specification: it is Project Reactor. How is it in details? 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 a different name.

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 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 implementing Subscriber. This class defines predefined methods, like hookOnSubscribe(), hookOnNext(), hookOnComplete(), hookOnError(), hookOnCancel(), and hookFinally(), help use can develop Subscriber part of Reactive Streams application.

OK, now let’s try an example.

First, we will define a object 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 Publisher publish a 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


Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment