首页 > 解决方案 > 当我将延迟运算符添加到第二个订阅时,共享一个 observable 变为单播

问题描述

以下代码按预期工作:

    const source = interval(1000).pipe(
        take(5),    
        share()
  );

  source.subscribe(x => console.log('c1', x));
  setTimeout(() => {
    source.subscribe(x => console.log('c2', x));
  }, 2000);

产生以下输出: c1 0 c1 1 c1 2 c2 2 c1 3 c2 3 c1 4 c2 4

但是当我将第二个订阅更改为使用 delay(2000) 而不是 setTimeout() 时,我得到了一个不共享的不同流。

    const source = interval(1000).pipe(
        take(5),    
        share()
  );

  source.subscribe(x => console.log('c1', x));

  source.pipe(delay(2000)).subscribe(x => console.log('c2', x));

产生这个输出:

c1 0 c1 1 c1 2 c2 0 c1 3 c2 1 c1 4 c2 2 c2 3 c2 4

如何让第二个订阅者使用共享流?我显然不完全理解 RX 操作员是如何在幕后工作的。

标签: rxjsrxjs-observables

解决方案


usingsource.pipe(delay(2000))与 using 完全不同setTimeout()delay()运营商将延迟其来源的每次发射,这意味着您仍会立即进行两次订阅。

您可能想要做的是:

of(null)
  .pipe(
    delay(2000),
    switchMapTo(source),
  )
  .subscribe();

或者这应该做同样的事情:

concat(timer(2000), source)
  .subscribe();

推荐阅读