The buffer Operator
buffer accumulates values coming from the source observable into an internal storage, withholding them from the observer until the notifier observable fires. At that moment, all accumulated values are delivered together as one array, the storage is cleared, and the process repeats — buffering again until the next notification from the notifier.
A notable characteristic of buffer is that it may dispatch an empty array to the observer. This occurs when the notifier emits while the internal storage holds no values.
The operational flow of the operator is as follows:
- Establish a subscription to the source observable.
- Establish a subscription to the notifier observable.
- Upon each emission from the source observable, append the value to the internal storage.
- When the notifier observable emits, forward all values from the storage to the observer — even if the storage is empty.
- When either the source observable or the notifier observable completes, dispatch the complete notification to the observer.
- If an error is thrown by either source observable, propagate the error notification to the observer.
buffer emits the complete notification as soon as either the source or the notifier observable terminates.
Practical Application
buffer is commonly employed whenever batching is needed. For example, in scenarios where a costly operation — such as re-rendering the DOM — must be executed repeatedly over short intervals in response to stream updates, batching allows collecting multiple updates and processing them all at once rather than in rapid succession.
The example below demonstrates how buffer can be used to output an array of recent interval events each time a click occurs:
const clicks = fromEvent(document, 'click');
const intervalEvents = interval(1000);
const buffered = intervalEvents.pipe(buffer(clicks));
buffered.subscribe(x => console.log(x));
