What are the rules for the Subscriber interface in Java 9?


Subscriber interface subscribes to publishers to receive items through onNext() method, error message through the onError() method, or a signal that no more items to be expected through the onComplete() method. Before any of those things happen, the publisher calls onSubscription() method.

public interface Subscriber<T> {
   public void onSubscribe(Subscription s);
   public void onNext(T t);
   public void onError(Throwable t);
   public void onComplete();
}

Rules for Subscriber interface:

  • A Subscriber must call through Subscription.request(long n) method to receive onNext() signals.
  • Subscriber.onComplete() and Subscriber.onError(Throwable t) methods must not call any methods on Subscription or Publisher.
  • Subscriber.onComplete() and Subscriber.onError(Throwable t) methods must consider the Subscription canceled after received a signal.
  • A Subscriber must call Subscription.cancel() method on a given Subscription after onSubscribe() signal if it already has an active Subscription.
  • A Subscriber must call Subscription.cancel() method if the Subscription no longer needed.
  • A Subscriber makes sure that all calls on its Subscription's request and cancel methods are performed serially.
  • A Subscriber must receive one or more onNext() signals after called Subscription.cancel() method if there are still requested elements pending. This method doesn't guarantee to perform underlying cleaning operations immediately.
  • A Subscriber must receive the onComplete() signal with or without a preceding Subscription.request(long n) call.
  • A Subscriber must receive an onError() signal with or without a preceding Subscription.request(long n) call.
  • A Subscriber makes sure that all calls on its signal methods happen before the processing of the respective signals. It means that the Subscriber must take care of properly publishing the signal to its processing logic.
  • Subscriber.onSubscribe() must call at most once for a given Subscriber.
  • Calling onSubscribe(), onNext(), onError() or onComplete() methods must returns except when any provided parameter is null in which case it must throw NullPointerException to the caller.

Updated on: 21-Apr-2020

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements