rxjs - 当我将延迟运算符添加到第二个订阅时,共享一个 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 操作员是如何在幕后工作的。
解决方案
usingsource.pipe(delay(2000))
与 using 完全不同setTimeout()
。delay()
运营商将延迟其来源的每次发射,这意味着您仍会立即进行两次订阅。
您可能想要做的是:
of(null)
.pipe(
delay(2000),
switchMapTo(source),
)
.subscribe();
或者这应该做同样的事情:
concat(timer(2000), source)
.subscribe();
推荐阅读
- php - CodeIgniter 4 过滤器 - 退出并响应
- excel - 在具有求和功能的Excel工作表中使用合并功能
- pytorch - RuntimeError: expected device cpu and dtype Float but got device cpu and dtype Bool
- .net - EF Core:外键返回空值:存储库模式
- selenium - 使用具有属性值的 xpath 查找元素
- java - 如何将子集合中的所有文档获取到 Firebase Firestore 中的 RecyclerView
- mysql - Ubuntu - 主机上的防火墙规则 MySQL | Docker 容器托管
- c++ - C++ 从十进制乘法中得到不准确的结果
- python - 在熊猫数据框中查找最新列
- snowflake-cloud-data-platform - 雪花 ifnull 和 parse_json 结合使用时无法按预期工作