热 Observable 和冷 Observable 是 RxJS 中两个核心概念,它们描述了数据流的执行和共享方式。
Cold Observable
// 冷 Observable - 像音乐 CD
const cold$ = new Observable(subscriber => {
console.log('开始执行'); // 每次订阅都会执行
subscriber.next(Math.random());
});
cold$.subscribe(x => console.log(`订阅者A: ${x}`));
cold$.subscribe(x => console.log(`订阅者B: ${x}`));
- 像函数调用 - 每次订阅都重新执行
- 数据生产是惰性的,有订阅才开始
- 每个订阅者有独立的数据流
- 典型的冷 Observable:
of,from,interval, HTTP 请求
Hot Observable
共享同一个执行,无论何时订阅:
// 热 Observable - 像现场音乐会
const hot$ = new Observable(subscriber => {
console.log('开始执行'); // 只执行一次!
subscriber.next(Math.random());
}).pipe(share());
hot$.subscribe(x => console.log(`订阅者A: ${x}`));
hot$.subscribe(x => console.log(`订阅者B: ${x}`));
// 输出:
// 开始执行
// 订阅者A: 0.789
// 订阅者B: 0.789
// 两个订阅者得到相同的随机数!
创建 Hot Observable
// 方法1:share 操作符可以将Cold Observable 变为 Hot Observable
const cold$ = interval(1000);
const hot$ = cold$.pipe(share());
// 方法二:Subject 创建
const subject = new Subject();
const hot$ = subject.asObservable();
// 方法三:使用 publish() + connect()
const hot$ = interval(1000).pipe(
publish()
);
const connection = hot$.connect(); // 开始执行
对比
| 特性 | 冷 Observable | 热 Observable |
|---|---|---|
| 数据生产 | 每次订阅创建新生产 | 共享同一个生产 |
| 执行时机 | 惰性,订阅时开始 | 独立于订阅 |
| 数据一致性 | 每个订阅者得到完整独立数据 | 订阅者可能错过早期数据 |
| 资源使用 | 可能重复创建资源 | 共享资源 |
| 典型用例 | HTTP 请求、计算函数 | 用户事件、WebSocket、状态管理 |