zl程序教程

您现在的位置是:首页 >  其它

当前栏目

[RxJS] Split an RxJS observable with window

with an window Rxjs split Observable
2023-09-14 09:00:52 时间

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.

 

'window' main task is to split observable to multi inner observables. That allows me do something useful to individual inner observable, such as 'scan' & 'count'.

 

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));