Flow programming: subscriber and publisher to keep track of count?

Viewed 480

I came over an article regarding the new Flow related interfaces in Java9. Example code from there:

public class MySubscriber<T> implements Subscriber<T> {  
  private Subscription subscription;    
  @Override  
  public void onSubscribe(Subscription subscription) {  
    this.subscription = subscription;  
    subscription.request(1); //a value of  Long.MAX_VALUE may be considered as effectively unbounded  
  }        
  @Override  
  public void onNext(T item) {  
    System.out.println("Got : " + item);  
    subscription.request(1); //a value of  Long.MAX_VALUE may be considered as effectively unbounded  
   }  

As you can see, onNext() requests one new item to be pushed.

Now I am wondering:

  • if onSubscribe() requested, say 5 items
  • and after the first item gets delivered, request(1) is called like above

Is the server now expected to send

  • five items ( 5 requested. -1 sent. +1 requested)
  • or one item (because the previous request gets "discarded" by that new request)

In other words: when request() is called several times, do those numbers add up; or are previous requests "discarded"?

Leading to the question title - whether the subscriber needs to keep track about received items, in order to avoid requesting "too many" items at some point.

2 Answers
Related