How can we implement the Subscriber interface in Java 9?

JavaObject Oriented ProgrammingProgramming

Java 9 supports to create Reactive Streams by introducing a few interfaces: Publisher, Subscriber, Subscription, and SubmissionPublisher class that implements the Publisher interface. Each interface can play a different role corresponding to the principles of Reactive Streams.

We can use the Subscriber interface to subscribe to the data that is being published by a publisher. We need to implement the Subscriber interface and provide an implementation for the abstract methods.

Flow.Subscriber interface methods:

  • onComplete(): This method has been called when the Publisher object completes its role.
  • onError(): This method has been called when something goes wrong in Publisher and is notified to the Subscriber.
  • onNext(): This method has been called whenever Publisher has new information to be notified to all Subscribers.
  • onSubscribe(): This method has been called when Publisher adds Subscriber.

Example

import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
import java.util.stream.IntStream;

public class SubscriberImplTest {
   public static class Subscriber implements Flow.Subscriber<Integer> {
      private Flow.Subscription subscription;
      private boolean isDone;
      
      @Override
      public void onSubscribe(Flow.Subscription subscription) {
         System.out.println("Subscribed");
         this.subscription = subscription;
         this.subscription.request(1);
      }
      @Override
      public void onNext(Integer item) {
         System.out.println("Processing " + item);
         this.subscription.request(1);
      }
      @Override
      public void onError(Throwable throwable) {
         throwable.printStackTrace();
      }
      @Override
      public void onComplete() {
         System.out.println("Processing done");
         isDone = true;
      }
   }
   public static void main(String args[]) throws InterruptedException {
      SubmissionPublisher<Integer> publisher = new SubmissionPublisher<>();
      Subscriber subscriber = new Subscriber();
      publisher.subscribe(subscriber);
      IntStream intData = IntStream.rangeClosed(1, 10);
      intData.forEach(publisher::submit);
      publisher.close();
      while(!subscriber.isDone) {
         Thread.sleep(10);
      }
      System.out.println("Done");
   }
}

Output

Subscribed
Processing 1
Processing 2
Processing 3
Processing 4
Processing 5
Processing 6
Processing 7
Processing 8
Processing 9
Processing 10
Processing done
Done
raja
Published on 13-Apr-2020 17:21:04
Advertisements