RxJS - Transformation Operator bufferToggle



In the case of bufferToggle it takes 2 arguments, openings and closingSelector. The opening arguments are a subscribable or a promise to start the buffer and the second argument closingSelector is again subscribable or promise an indicator to close the buffer and emit the values collected.

Syntax

bufferToggle(openings: SubscribableOrPromise, closingSelector: SubscribableOrPromise): Observable

Parameters

openings − A promise or notification to start the new buffer.

closingSelector − A function that will take the values from openings observable and return Subscribable or promise.

Return value

An observable will be returned, that will have an array of buffered values.

Example

import { fromEvent, interval,EMPTY} from 'rxjs';
import { bufferToggle } from 'rxjs/operators';

let btn = document.getElementById("btnclick");
let btn_clicks = fromEvent(btn, 'click');
let start = interval(2000);
let buffered_array = btn_clicks.pipe(
   bufferToggle(start, a => a%2 ==0 ? interval(1000): EMPTY)
);
buffered_array.subscribe(arr => console.log(arr));

In the example above the buffer will start after 2s and end when we 1s interval if the value received is even otherwise it will empty the buffer values and emit empty values.

Output

bufferToggle Operator
Advertisements