Rxjs scan clonned on subscribe

Viewed 36

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.

1 Answers

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>

Related