All you need to know about the buffer operator in RxJS
Buffers the source Observable values until closingNotifier emits.Collects values from the past, i.e which were not emitted and waits for the next emit from the notifier.
In simple words we can say the buffer operator waits till another provided observable emits,and as soon as the inner observable emits, it collects the previously emitted values from the source, combines them in an array and emits them.
Signature
buffer(closingNotifier: Observable<any>): OperatorFunction
closingNotifier: An observable that emits to notify
OperatorFunction: Function that emits the output as an observable
A sample code snippet for the buffer operator is given below.
const intervalObs = interval( 1000 ).pipe(take( 10 )); // (1)const timeInterval = interval( 4000 ); // (2)const ob$ = intervalObs.pipe(buffer(timeInterval)); // (3)ob$.subscribe(val => console.log(val)); // (4)
In step 1, we create an observable called intervalObs through the interval operator and take only the first 10 emissions. In the second step we create another observable through the interval operator again, but it emits values after every 4000 ms. Then in the next step, we pipe the intervalObs through the buffer operator with the timeInterval observable as parameter and assign it to a constant value called ob$. As with other observable, we subscribe to it and print the value onto the console.
The result of the above code snippet comes out as follows.
// [0, 1, 2]// [3, 4, 5, 6]
After printing [3, 4, 5, 6] which is the collection of the past values after printing 2, the interval observable completes and so there is no further emission by the buffer operator.
These are the minimum concepts you need to know about the buffer operator.