天天看点

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的用法

继续阅读