[RxJS] Hot Observable, by .share()

.share() is an alias for .publish().refCount().

So if the source is not yet completed, no matter how many subscribers subscribe to the source, they share the same source. 

复制代码
const clock$ = Rx.Observable.interval(500).share().take(6);

const randomNum$ = clock$
  .map(i => Math.random() * 100).share();

const smallNum$ = randomNum$
  .filter(x => x <= 50)
  .toArray();

const largeNum$ = randomNum$
  .filter(x => x > 50)
  .toArray();

randomNum$.subscribe(x => console.log('random: ' + x));
smallNum$.subscribe(x => console.log('small:', x));
largeNum$.subscribe(x => console.log('large:', x));

/*

Console Run  Clear
"random: 49.87840398986816"
"random: 75.01024609865293"
"random: 32.59613439667008"
"random: 63.4234109489461"
"random: 35.58020574147034"
"random: 74.94599860014348"
"small:"
[49.87840398986816, 32.59613439667008, 35.58020574147034]
"large:"
[75.01024609865293, 63.4234109489461, 74.94599860014348]
*/
复制代码

 

It is important to know share the same source is only before the source stream completed, if it is already completed, then the new subscribers will trigger another source running.

For example, in the code, we change largeNum$ happens after 4s of first subscriber.

setTimeout(() => largeNum$.subscribe(x => console.log('large:', x)), 4000)

Because source will complete after 3s, therefor it will trigger a new source:

复制代码
/*
"random: 74.91154828671043"
"random: 10.964684522348733"
"random: 29.076967396825903"
"random: 20.070493440627235"
"random: 22.44421045844409"
"random: 14.233614544120798"
"small:"
[10.964684522348733, 29.076967396825903, 20.070493440627235, 22.44421045844409, 14.233614544120798]
"large:"
[93.04544926644354, 65.4090612653734, 67.15475480984114]
*/
复制代码

As we can see, in the large array, all the numbers are not from random we log out before.

posted @   Zhentiw  阅读(751)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-05-31 [RxJS] Transformation operator: repeat
2016-05-31 [RxJS] Error handling operator: catch
2016-05-31 [Angular 2] Keynote: Lazy Routing -- NGCONF
点击右上角即可分享
微信分享提示