Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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));
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!