'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:

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?



Solution 1:[1]

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

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

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

Solution 2:[2]

As documentation says

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

accumulator function return type of mergeScan should be 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.

if you replace mergeScan` with scan in this line and log like below

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: ƒ}

But if you use maergeScan we will see the log like 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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2