javascript - Rxjs 在订阅时克隆扫描

我不明白 rxjs 中的某些内容。当有人:

  1. 有时点击墨水按钮
  2. 然后点击第二个订阅按钮
  3. 然后在 inc 按钮上重新单击几次

为什么看起来 accumulator observable 在第二次订阅期间被克隆了?谢谢。

<!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>

注意:我是 JavaScript 新手。

回答1

这与 rx 的关系比与 javascript 的关系更大。查看冷热可观察对象之间的区别,您会发现可以让您在多个订阅者之间共享流的运算符。

<!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>

相似文章

随机推荐

最新文章