How to implement reactive streams using Flow API in Java 9?

JavaObject Oriented ProgrammingProgramming

Flow API is official support for reactive streams specification since Java 9. It is a combination of both Iterator and Observer patterns. The Flow API is an interoperation specification and not an end-user API like RxJava.

Flow API consists of four basic interfaces:

  • Subscriber: The Subscriber subscribes to Publisher for callbacks.
  • Publisher: The Publisher publishes the stream of data items to the registered subscribers.
  • Subscription: The link between publisher and subscriber.
  • Processor: The processor sits between Publisher and Subscriber, and transforms one stream to another.

In the below example, we have created a basic subscriber that asks for one data object, prints it and asks for one more. We can use a publisher implementation provided by Java (SubmissionPublisher) to complete our session.

Example

import java.util.concurrent.Flow;
import java.util.List;
import java.util.concurrent.SubmissionPublisher;

class MySubscriber<T>implements Flow.Subscriber<T> {
   private Flow.Subscription subscription;
   @Override
   public void onSubscribe(Flow.Subscription subscription) {
      this.subscription = subscription;
      this.subscription.request(1);
   }
   @Override
   public void onNext(T item) {
      System.out.println(item);
      subscription.request(1);
   }
   @Override
   public void onError(Throwable throwable) {
      throwable.printStackTrace();
   }
   @Override
   public void onComplete() {
      System.out.println("Done");
   }
}

// main class
public class FlowTest {
   public static void main(String args[]) {
      List<String> items = List.of("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
      SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
      publisher.subscribe(new MySubscriber<>());
      items.forEach(s -> {
         try {
            Thread.sleep(1000);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
         publisher.submit(s);
      });
      publisher.close();
   }
}

Output

1
2
3
4
5
6
7
8
9
10
Done
raja
Published on 27-Mar-2020 08:22:11
Advertisements