buffer() operator

The idea with the buffer() operator is that we can collect a bunch of events without them being emitted straight away. The operator itself takes an argument, an Observable that defines when we should stop collecting events. At that point in time, we can choose what to do with those events. Here is how you can use this operator:

// grouping/buffer.js

const elem = document.getElementById("input");

let keyStream$ = Rx.Observable.fromEvent(elem,"keyup");
let breakStream$ = keyStream$.debounceTime(2000);
let chatStream$ = keyStream$
.map(ev => ev.key)
.filter(key => key !== "Backspace")
.buffer(breakStream$)
.switchMap(newContent => Rx.Observable.of("send text as I type", newContent));

chatStream$.subscribe(data=> console.log(data));

What this does is to collect events until there has been 2 seconds of inactivity. At that point, we release all the key events we have buffered up. When we release all those events, we can, for example, send them somewhere via AJAX. This is a typical scenario in a chat application. Using the preceding code, we can always send the latest character that has been typed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.207.70