Scala Reactive Programming
上QQ阅读APP看书,第一时间看更新

Flow API – Subscription

In the Flow API, a Subscription works as a mediator or interface between two other important components, Publisher and Subscriber. It connects those components and works as a message controller or channel so that a Publisher can emit data into a Subscription and one or more subscribers who subscribe to that Publisher and receive data from that Subscription:

In the Java 9 Flow API, this Subscription is an interface with a set of methods and is defined as follows:

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

It contains the following two methods to control the messaging between Publisher and Subscriber(s):

  • request(): This is used to add the given n number of items to the current active Subscription between Publisher and Subscriber(s)
  • cancel(): This is used to cancel or stop the current Subscription between Publisher and Subscriber(s) so that there is no communication happening between them

One Subscription is dedicated between a Publisher and a single Subscriber or a set of Subscribers. Once it's stopped by making a call to the cancel() method, Publisher cannot send data to it or Subscriber cannot receive any messages from it.

It is also defined within another class as a static component. We will see it in the next section.