[英]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.