# What are the rules for the Publisher interface in Java 9?

JavaObject Oriented ProgrammingProgramming

A Publisher is a provider of an unbounded number of sequenced elements publishing them according to demand received from its Subscribers. Publisher<T> interface is responsible for publishing elements of type T and provides a subscribe() method for subscribers to connect to it.

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

Rules for Publisher interface:

• The total number of onNext() methods signaled by Publisher to a Subscriber must be less than or equal to a total number of elements requested by Subscriber´s Subscription at all times.
• A Publisher may signal fewer onNext() methods than requested, and terminate the Subscription by calling onComplete() or onError() methods.
• The onSubscribe(), onNext(), onError(), and onComplete() methods signaled to a Subscriber must be signaled serially.
• If Publisher fails, then it must signal an onError() method.
• If Publisher terminates successfully, then it must signal an onComplete() method.
• If Publisher signals either onError() or onComplete() method on Subscriber, then Subscriber’s Subscription must be canceled.
• Once terminal state has signaled (onError(), onComplete()), it is required that no further signals can occur.
• If Subscription is canceled, its Subscriber must stop being signaled.
• Publisher.subscribe() method must call onSubscribe() method on the provided Subscriber prior to any other signals to that Subscriber and returns normally, except when the provided Subscriber is null. In this case, it must throw a NullPointerException to the caller.
• Publisher.subscribe() method may call as many times as required with a different Subscriber each time.
• A Publisher may support multiple Subscribers and decides whether each Subscription can be unicast or multicast.
Published on 22-Apr-2020 19:52:48