RxJS:shareReplay 中的 bufferSize 是什么?

WHI*_*LOR 6 rxjs

我不明白bufferSize参数是什么意思,它有什么作用。

以下有什么区别?

var published = source
    .shareReplay();

var published = source
    .shareReplay(0)

var published = source
    .shareReplay(1);

var published = source
    .shareReplay(10);
Run Code Online (Sandbox Code Playgroud)

Mab*_*abd 13

缓冲区大小 :

  • BufferSize 表示缓存和重播的项目数
  • 订阅时,它将重播特定数量的排放
  • 即使没有订阅者,项目仍处于缓存状态

来到问题:

var published = source
    .shareReplay();
Run Code Online (Sandbox Code Playgroud)

任何订阅者都将获得源发出的所有项目/数据流

var published = source
    .shareReplay(0)
Run Code Online (Sandbox Code Playgroud)

它将缓存最后发出的值

var published = source
    .shareReplay(1);
Run Code Online (Sandbox Code Playgroud)

它将缓存最后发出的值,与上面相同

var published = source
    .shareReplay(10);
Run Code Online (Sandbox Code Playgroud)

它将缓存源发出的最后 10 个项目。

更多信息: 我将用一个例子来解释这个概念。

 let source$ = interval(1000)
  .pipe(
    take(5),
    shareReplay(3)
  )
source$.subscribe(res => console.log('1st time=>', res))

setTimeout(() => {
  source$.subscribe(res => console.log('2nd time=>', res))
}, 5000)
Run Code Online (Sandbox Code Playgroud)

注意:这里的第一个订阅只是意味着开始发出值。当我使用take运算符来限制发射间隔时,它将发射值五次 它将导致输出:

1st time=> 0
1st time=> 1
1st time=> 2
1st time=> 3 
1st time=> 4
Run Code Online (Sandbox Code Playgroud)

现在只需关注第二个可观察值:我们可以看到 bufferSize 值设置为 3,因此它将记录最后三个发出的值

2nd time=> 2
2nd time=> 3
2nd time=> 4
Run Code Online (Sandbox Code Playgroud)


WHI*_*LOR 5

source     --1--2--3--4--5--6--7
subscriber -----------S---------
Run Code Online (Sandbox Code Playgroud)

source.shareReplay(2) subscriber将得到[2, 3, 4, 5,...]

  • 你能解释一下为什么订阅者会得到 [2, 3, 4, 5, ...] (3认同)
  • 因为它在共享流发出 4 的那一刻订阅,因为有 shareReplay(2),流将为它重放 2 个先前的值 2 和 3 (2认同)