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

Flow API – Publisher

As its name suggests, Publisher is a component that works as a Producer of data, which means it emits the data. It acts as a source of data, so it is also known as Producer, Source of data, or emitter:

In the Java 9 Flow API, this Publisher is an interface with the subscribe method and is defined with the following signature:

public interface Publisher<T> {   
  public void subscribe(Subscriber<? super T> subscriber);   
}       

Here, the subscribe() method is taking a single parameter of type Subscriber, which is another component of the Flow API. One publisher can subscribe one or more subscribers to it. It is defined within another class as a static component. We will see it in the following section.

Publisher uses this subscribe() method to subscribe or register its subscribers, as shown here.

Go through the following pseudo-code for Subscriber.subscribe() function usage:

Subscriber sub = Receive a Request from a Subscriber 
Publisher pub = ... 
pub.subscribe(sub) 

Publisher receives a request from a subscriber and executes pub.subscribe(sub) to register that subscriber with it. Once that subscription is created, the publisher sends data to those registered parties.

For instance, we can use a data store, file, collection, server, and more, as a source of data to emit data for subscribers.