rxjs里scan和mergeScan operators的用法

时间:2022-07-28
本文章向大家介绍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 click$ = fromEvent(document, 'click');
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));

唯一的区别就在于下图高亮之处:返回的是累加的Observable而不是原始值: