[RxJS] Share data among multiple subscribers with Subjects
Subject as resource can be shared amount multi observers.
Normal Observable pattern is Cold observable, each subscription will get its own resource:
import { interval, Subject } from "rxjs";
import { tap } from "rxjs/operators";
const observer = {
next: (val) => console.log("next", val),
error: (err) => console.error("error", err),
complete: () => console.log("complete"),
};
const subject = new Subject();
const interval$ = interval(2000).pipe(
tap((val) => console.log("new interval", val))
);
// Each subscription is getting its own interval
// rather than one interval being shared between both
interval$.subscribe(observer);
interval$.subscribe(observer);
When we swtich to Subject:
import { interval, Subject } from "rxjs";
import { tap } from "rxjs/operators";
const observer = {
next: (val) => console.log("next", val),
error: (err) => console.error("error", err),
complete: () => console.log("complete"),
};
const subject = new Subject();
const interval$ = interval(2000).pipe(
tap((val) => console.log("new interval", val))
);
/*
// Each subscription is getting its own interval
// rather than one interval being shared between both
interval$.subscribe(observer);
interval$.subscribe(observer);
*/
const subscription = subject.subscribe(observer);
const subscriptionTwo = subject.subscribe(observer);
// Interval only got log out once
// And next value log out twice by two subscirptions
// Subject is multicasting, sharing the observable
// It is useful when you have expanse resourse such as
// Web stock socket$.subscribe(subject)
interval$.subscribe(subject);
Well, there is easier way to achieve the same effect by using share():
import { interval } from "rxjs";
import { share, shareReplay, tap } from "rxjs/operators";
const observer = {
next: (val) => console.log("next", val),
error: (err) => console.error("error", err),
complete: () => console.log("complete"),
};
const interval$ = interval(2000).pipe(
tap((val) => console.log("new interval", val)),
share()
);
interval$.subscribe(observer);
interval$.subscribe(observer);
分类:
RxJS
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-09-15 [CSS3] Use CSS Variables to Maintain the Aspect Ratio for an Element
2020-09-15 [GraphQL] Multi Query and Alias
2020-09-15 [Machine Learning] Gradient Checking
2019-09-15 [ARIA] What is Accessible Name Calculation?
2019-09-15 [ARIA] Accessible animations with reduced motion
2019-09-15 [ARIA] Accessible modal dialogs
2018-09-15 [Tools] Scroll, Zoom, and Highlight code in a mdx-deck slide presentation with Code Surfer <🏄/>