Reactive Java World — 1

Sivaram Rasathurai
2 min readMar 31, 2022

Reactive Streams Specification has four interfaces to talk in a reactive way between the applications.

Four Interfaces are

  1. Publisher
  2. Subscriber
  3. Subscription
  4. Processor

Basically, when we need to consume data then we will act as subscribers. and there will be a source that acts as a publisher. We have to tell the publisher that We are going to subscribe to you/ consume data from you. In that case, the publisher should have a method that can allow us to subscribe to it. luckily we have one method in publisher and it is called subscribe which can take subscriber as an argument.

public interface Publisher<T> {
void subscribe<Subsriber<? super T> var1);
}

Hence our subscriber will call this method in the publisher to tell it that our subscriber is willing to subscribe to you.

Our publisher also needs to tell the subscriber, you subscribed here it is your subscription.

Hence The Subscribe should have some mechanism to receive the subscription. Yes, the Subscriber has a method for that This method takes the subscription as a method parameter. basically, when the publisher calls this method it will give the subscription as well. There are some other methods also in this subscriber interface, I will cover them later part of this post.

public interface Subsriber<T> {
void onSubsribe(Subscription var1);
}

So we got to know that we have a subscription that connects the publisher and subscriber.

It has two methods as below

public interface Subscription {
void request(long var1);
void cancel();
}

This request method has one parameter and it controls how much data can be carried out through this subscription. and cancel can be used to cancel the subscription.

Sometimes we need to act as a subscriber as well as a publisher, in that case, we can use processor. Processors can behave as publishers and subscribers.

interface Processor<T,R> extends Subsriber<T>, Publisher<R> {}

When publishers push some data to subscribers, there can be three things happens

  1. Success
    When an item needs to be sent publisher will use this way to send it. For this, subscribe has a method onNext that can be used to push an item to the subscriber.
  2. Error
    When the publisher needs to tell that some error happens then it will notify the subscriber with the onError Method. In this case
  3. onComplete
    Somehow publisher needs to tell the subscriber that, I sent all items to you as you requested with the subscription. This method of the subscriber is used for that.
public interface Subsriber<T> {
void onSubsribe(Subscription var1);
void onNext(T var1);
void onError(Throwable var1);
void onComplete();
}

--

--