[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);

 

posted @   Zhentiw  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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 <🏄/>
点击右上角即可分享
微信分享提示