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

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 <strong>Flow.Subscriber<T></strong> {
   private <strong>Flow.Subscription</strong> subscription;
   <strong>@Override</strong>
   public void <strong>onSubscribe</strong>(Flow.Subscription subscription) {
      this.subscription = subscription;
      this.subscription.request(1);
   }
   <strong>@Override</strong>
   public void <strong>onNext</strong>(T item) {
      System.out.println(item);
      subscription.request(1);
   }
   <strong>@Override</strong>
   public void <strong>onError</strong>(Throwable throwable) {
      throwable.printStackTrace();
   }
   <strong>@Override</strong>
   public void <strong>onComplete</strong>() {
      System.out.println("Done");
   }
}

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

Output

<strong>1
2
3
4
5
6
7
8
9</strong>
<strong>10
Done</strong>
Updated on: 2020-03-27T08:22:11+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements