天天看點

rxjs裡scan和mergeScan operators的用法

mergeScan

Applies an accumulator function over the source Observable where the accumulator function itself returns an Observable, then each intermediate Observable returned is merged into the output Observable.

It’s like scan, but the Observables returned by the accumulator are merged into the outer Observable.

看個差別。

先用scan:

const click$ = fromEvent(document, 'click');

   const one$ = click$.pipe(mapTo(1));

   const seed = 0;

   const count$ = one$.pipe(

   scan((acc, one) => (acc + one), seed),

每次點選ui,會顯示目前總的點選次數。

用mergeScan的實作:

const one$ = click$.pipe(mapTo(1));

const seed = 0;

const count$ = one$.pipe(

 mergeScan((acc, one) => of(acc + one), seed),

);

count$.subscribe(x => console.log(x));

rxjs裡scan和mergeScan operators的用法

繼續閱讀