rxjs - 如何将这种冷的可观察到的变成热的?
问题描述
我似乎无法将这个冷的可观察到的变成热的:
const test = new BehaviorSubject('test').pipe(tap(() => console.log('I want this to be logged only once to the console!')))
const grr = test.pipe(
share(), // share() seems to not do anything
take(1), // The culprit is here, causes logging to take place 5 times (5 subscribers)
share() // share() seems to not do anything
)
grr.subscribe(() => console.log(1))
grr.subscribe(() => console.log(2))
grr.subscribe(() => console.log(3))
grr.subscribe(() => console.log(4))
grr.subscribe(() => console.log(5))
// Expected output:
// 'I want this to be logged only once to the console!'
// 1
// 2
// 3
// 4
// 5
我应该如何改变它以产生想要的输出?
解决方案
您可以像这样使用publishReplay
和refCount
运算符:
import { interval, BehaviorSubject } from 'rxjs';
import { publishReplay, tap, refCount } from 'rxjs/operators';
const test = new BehaviorSubject('test').
pipe(
tap(() => console.log('I want this to be logged only once to the console!')
),
publishReplay(1),
refCount()
);
test.subscribe(() => console.log(1));
test.subscribe(() => console.log(2));
test.subscribe(() => console.log(3));
test.subscribe(() => console.log(4));
工作 Stackblitz:https ://stackblitz.com/edit/typescript-cvcmq6?file=index.ts
推荐阅读
- reporting-services - SSRS 报告的自动化测试
- python - 在 Raspberry Pi 上自动上传到 Dropbox
- google-cloud-platform - Google Cloud Storage - 文件未显示
- python - Python Ctype标题不同的语言
- javascript - 事件触发时未调用 Javascript(仅使用 $(document).ready)
- rest - 没有 EF(实体框架)的 OData Web API
- python - xlwings 和 win32api 的问题
- arrays - 在表格视图中按日期过滤数组
- python - 如何使用 Google Natural Processing API 从文本中提取电子邮件?
- c++ - MSVC:未解析的外部符号“__imp_JNI_GetCreatedJavaVMs”