【问题标题】:why the 'refcount: true' of `ShareReplay` doesn't work like `share` when source completes为什么当源完成时“ShareReplay”的“refcount:true”不像“share”那样工作
【发布时间】:2021-12-15 07:55:56
【问题描述】:

我试过https://medium.com/volosoft/whats-new-in-rxjs-7-a11cc564c6c0给出的例子

import { interval, of, zip } from "rxjs";
import { map, shareReplay } from "rxjs/operators";

const shared$ = zip(interval(1000), of("A", "B", "C", "D", "E")).pipe(
  map(([, char]) => char),
  shareReplay({ refCount: true, bufferSize: 3 })
);

shared$.subscribe(a => console.log('a: ', a);
// (~1s apart) A, B, C, D, E

setTimeout(() => shared$.subscribe(b => console.log('b: ', b), 6000);
// (after ~6s, all at once) C, D, E

我认为 'b' 订阅会再次输出 'A, B .... E'。因为 'a' sub 已在 5000 毫秒内完成,所以 refCount 应该变为 0。然后 shared$ 断开与源的连接。因此,当 b 订阅 shared$ 时,源将重新启动。但控制台只显示由 shareReplay 重播的“C、D、E”。

如果我用share() 替换shareReplay({refCount: true}) 或将take(5) 添加到'a',b 将按我的预期输出。根本原因是什么? 你可以玩我的代码:https://stackblitz.com/edit/azerz8?devtoolsheight=50

【问题讨论】:

    标签: rxjs


    【解决方案1】:

    好的。我得到了答案。

    成功完成的源将永远缓存在 shareReplayed observable 中。

    这是来自贡献者的答案。 https://github.com/ReactiveX/rxjs/discussions/6731

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-12
      • 2011-05-13
      • 2011-06-08
      • 1970-01-01
      • 2015-10-12
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多