简体   繁体   English

RxJS 合并扫描与扫描

[英]RxJS mergeScan vs scan

I am learning RxJS and I can't figure out the difference between scan and mergeScan of the RxJS. Both examples:我正在学习 RxJS,我无法弄清楚 RxJS 的 scan 和 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));

... and ... 和

const click$ = fromEvent(document, 'click');
const one$ = click$.pipe(mapTo(1));
const seed = 0;
const count$ = one$.pipe(scan((acc, one) => (acc + one), seed));
count$.subscribe((x) => console.log(x));

... produce the same results (number of mouse clicks) - so what is the difference? ...产生相同的结果(鼠标点击次数)——那么有什么区别呢? Are they both needed?他们都需要吗?

mergeScan can execute observable inside but scan cannot, a typical use case would be something like inifite scroll that you want to call the endpoint continuously mergeScan可以在内部执行 observable 但scan不能,一个典型的用例是像 inifite scroll 你想连续调用端点

const click$ = fromEvent(loadmore, 'click');
const count$ = click$.pipe(
  mergeScan((acc, one) => httpGetPage(acc.pageCusor+1).pipe(map(res=>{
    return {pageCusor:pageCusor++,contet.concat(res)}
})), {pageCursor:0,content:[]}),
);

To examine, you can try console.log in your scan example and try return a of(value) , it will show Observable要检查,您可以在scan示例中尝试 console.log 并尝试返回一个of(value) ,它将显示Observable

const count$ = one$.pipe(scan((acc, one) => of(acc + one), seed));
count$.subscribe((x) => console.log(x));

As documentation says正如文档所说

It's like scan, but the Observables returned by the accumulator are merged into the outer Observable.就像scan一样,只是将累加器返回的Observable合并到外层的Observable中。

accumulator function return type of mergeScan should be ObservableInput累加器 function mergeScan的返回类型应该是ObservableInput

mergeScan 1st performs the scan operation and then subscribe to inner observable which is returned by accumulator function and store it acc and emits the same. mergeScan 1st 执行scan操作,然后订阅由累加器 function 返回的内部可观察对象并将其存储在acc中并发出相同的内容。

if you replace mergeScan` with scan in this line and log like below如果您在此行中将 mergeScan` 替换为 scan 并记录如下

scan((acc, one) => {
    console.log("acc ",acc);
    return of(acc + one);
  }, seed),

you will see acc value storing as an Observable .Log will be like this acc Observable {_subscribe: ƒ}您会看到acc值存储为Observable 。Log 将像这样acc Observable {_subscribe: ƒ}

But if you use maergeScan we will see the log like acc 1但是,如果您使用maergeScan ,我们将看到类似acc 1的日志

So moral of the story is,if your accumulator function returns observable the you have to use mergeScan otherwise scan will be fine所以这个故事的寓意是,如果你的累加器 function 返回可观察的你必须使用mergeScan否则scan就可以了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM