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

114
Views
Rxjs scan clonned on subscribe

I don't understand something in rxjs. Why is this reproductible example creating a second, reinitialized instance of counter, when someone:

  1. clicks some times on the inc button
  2. then clicks on the second subscribe button
  3. then reclicks some times on the inc button

Why does it look like the accumulator observable was cloned during the second subscribe ? Thanks.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Reprex rxjs</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js">
    </script>
</head>
<body>
<button id="inc_button">Click me to increase</button>
<button id="go_button">Start second counter</button>
</div>
<script>
    let score_calc = rxjs
        .fromEvent(document.getElementById('inc_button'), 'click')
        .pipe(rxjs.operators.scan(acc => acc+1, 0));
        
    score_calc.subscribe(x => console.log('score1',x));
    
    rxjs
        .fromEvent(document.getElementById('go_button'), 'click')
        .pipe(rxjs.operators.first())
        .subscribe(()=> score_calc.subscribe(x => console.log('score2',x)));
</script>
</body>
</html>

Note : I'm a JavaScript newbie.

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

0

This has more to do with rx than javascript. Look up the difference between hot and cold observables and you'll find operators that let you share streams between multiple subscribers.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Reprex rxjs</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js">
    </script>
</head>
<body>
<button id="inc_button">Click me to increase</button>
<button id="go_button">Start second counter</button>
</div>
<script>
    let score_calc = rxjs
        .fromEvent(document.getElementById('inc_button'), 'click')
        .pipe(
          rxjs.operators.scan(acc => acc+1, 0),
          rxjs.operators.shareReplay(1)
         );
        
    score_calc.subscribe(x => console.log('score1',x));
    
    rxjs
        .fromEvent(document.getElementById('go_button'), 'click')
        .pipe(rxjs.operators.first())
        .subscribe(()=> score_calc.subscribe(x => console.log('score2',x)));
</script>
</body>
</html>

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!