RxJS:shareReplay 中的 bufferSize 是什么?

RxJS: what is bufferSize in shareReplay?

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

以下有什么区别?

var published = source
    .shareReplay();

var published = source
    .shareReplay(0)

var published = source
    .shareReplay(1);

var published = source
    .shareReplay(10);
source     --1--2--3--4--5--6--7
subscriber -----------S---------

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

缓冲区大小:

  • BufferSize 表示缓存和重放的项目数
  • 在订阅时,它会重播特定数量的发射
  • 项目保持缓存状态,即使没有订阅者也是如此

开始提问:

var published = source
    .shareReplay();

任何订阅者都将获得源

发出的所有items/stream数据
var published = source
    .shareReplay(0)

它将缓存最后发出的值

var published = source
    .shareReplay(1);

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

var published = source
    .shareReplay(10);

它将缓存源发出的最后 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)

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

1st time=> 0
1st time=> 1
1st time=> 2
1st time=> 3 
1st time=> 4

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

2nd time=> 2
2nd time=> 3
2nd time=> 4