[rxjs] Demystifying Cold and Hot Observables in RxJS

Cold:

复制代码
console.clear();
var Observable = Rx.Observable;
var clock = Observable.interval(1000).take(10).map((i) => `${i}!`);
clock.subscribe((x) => {
  console.log(` a  ${x}`);
});

setTimeout(function(){
  clock.subscribe((x) => {
    console.log(`         b    ${x}`);
  });
}, 3500);
复制代码

Results:

复制代码
/*
" a  0!"
" a  1!"
" a  2!"
" a  3!"
"         b    0!"
" a  4!"
"         b    1!"
" a  5!"
"         b    2!"
" a  6!"
"         b    3!"
" a  7!"
"         b    4!"
" a  8!"
"         b    5!"
" a  9!"
"         b    6!"
"         b    7!"
"         b    8!"
"         b    9!"
*/
复制代码

As you can see, 'a' and 'b' all start from '0'. They are independent. As youtube vedio, you can open the same vedio in tow tabs. When you click play, those two vedio will play independently. 

 

Hot: publish().refCount();

Hot Observables are like 'live' youtube video, everyone watch the same vedio at the same pace. 

As I wrote in previous article about publish(); you can use this with connect() funciton, but there is problem, we will miss the very first event.

RefCount and a hot observable is analogous to a live video of a band playing at a concert, but the band doesn't start playing if there isn't anyone in the audience. That would be a waste, right? So, why play if there is no one watching?

RefCount tells the band to play when there is at least one person in the audience, in other words, when the number of observers goes from zero to one.

复制代码
console.clear();
var Observable = Rx.Observable;
var clock = Observable.interval(1000).take(10).map((i) => `${i}!`).publish().refCount();
clock.subscribe((x) => {
  console.log(` a  ${x}`);
});

setTimeout(function(){
  clock.subscribe((x) => {
    console.log(`         b    ${x}`);
  });
}, 3500);
复制代码

Results:

复制代码
/*" a  0!"
" a  1!"
" a  2!"
" a  3!"
"         b    3!"
" a  4!"
"         b    4!"
" a  5!"
"         b    5!"
" a  6!"
"         b    6!"
" a  7!"
"         b    7!"
" a  8!"
"         b    8!"
" a  9!"
"         b    9!"
*/
复制代码

 

posted @   Zhentiw  阅读(226)  评论(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工具
点击右上角即可分享
微信分享提示