天天看点

[RxJS] Split an RxJS observable with window

Mapping the values of an observable to many inner observables is not the only way to create a higher order observable. RxJS also has operators that take a first order observable and return a higher order Observable. In this lesson we will learn about window, an operator to split an observable.

const clickObservable = Rx.Observable.fromEvent(document, 'click');
const clockObservable = Rx.Observable.interval(1000);

const resultObservable = clockObservable
  .window(clickObservable)
  .map(obs => obs.count())
  .switch();

/*
--0---1---2---3---4---5---6---7---8|
--------c-----------c---c-----------

    window
    
+-------+-----------+---+----------+
\       \           \   \          \
--0---1-|-2---3---4-|-5-|-6---7---8|

      .map(o => o.count())
      
--------+-----------+---+---------+     
        \           \   \         \
-------2|----------3|--1|--------3|

      switch
      
--------2-----------3---1---------3      
*/

resultObservable
  .subscribe(x => console.log(x));