Hot Observable
Hot ObservableCharacteristicsExamplesWhen to use Hot ObservableCold ObservableCharacteristicsExamplesWhen to use Cold ObservableTurn Cold to Hot Observable1. subscribe Subject2. share or shareReplayConclusionReference
A hot observable is an observable that starts emitting data as soon as it is created, regardless of whether or not there are any subscribers. In other words, the data stream is always active and subscribers can only access the data that is emitted after they subscribe.
Characteristics
- Values produced outside of the observable (like
Subject
callsinstance.next()
)
- Shares produced values with multiple subscribers (Multicasting)
- Subjects are hot observable
import { Subject } from 'rxjs';
const subject = new Subject();
let i = 0;
setInterval(() => {
subject.next(i++);
}, 1000);
Examples
- Movie Theater: many audience watches the same movie in a room. Other people who don’t subscribe it outside the room, but the movie keeps playing (producing).
- Stock ticker. The stock ticker emits stock prices continuously, regardless of whether or not anyone is listening. If a subscriber wants to get the latest stock prices, they need to subscribe to the ticker.
import { Observable } from 'rxjs';
const ticker = new Observable(observer => {
const stockPrices = [10, 20, 30, 40, 50];
let index = 0;
const intervalId = setInterval(() => {
observer.next(stockPrices[index++]);
if (index === stockPrices.length) {
observer.complete();
clearInterval(intervalId);
}
}, 1000);
return {
unsubscribe() {
clearInterval(intervalId);
}
};
});
// Subscribe to the ticker
ticker.subscribe(price => console.log(`Price: ${price}`));
In this example, we create a
ticker
observable that emits stock prices every second. The observable emits data regardless of whether or not there are any subscribers. When a subscriber subscribes to the observable, they will receive the data that is emitted after they subscribe.When to use Hot Observable
Hot observables are useful when data is constantly changing and needs to be accessed by multiple subscribers. Hot observables are also useful when data needs to be shared between subscribers. For example, in a chat room, a hot observable can be used to share messages between users.
Cold Observable
A cold observable, on the other hand, is an observable that emits data only when there is a subscriber. In other words, the data stream is inactive until a subscriber subscribes to it.
Characteristics
- values produced inside of the observable
- re-executes logic for each subscriber
Examples
- Angular Http Request
- Angular reactive form API
- Netflix: stream videos, user can click start/pause. Different families can watch their own shows.
When to use Cold Observable
Cold observables are useful when data is static and only needs to be accessed by a single subscriber. Cold observables are also useful when data is expensive to generate and should only be generated when needed. For example, in an e-commerce site, a cold observable can be used to generate a product catalog when a user requests it.
Turn Cold to Hot Observable
1. subscribe Subject
If you have a cold observable and you want to turn it into a hot observable, you can use a
Subject
. A Subject
is both an observable and an observer, which means that it can both emit data and subscribe to other observables. You can create a Subject
and subscribe to the cold observable, and then subscribe to the Subject
to turn it into a hot observable.import { Subject } from 'rxjs';
import { coldObservable } from './example';
const subject = new Subject();
coldObservable.subscribe(subject);
subject.subscribe(data => console.log(`Subscriber 1: ${data}`));
subject.subscribe(data => console.log(`Subscriber 2: ${data}`));
In this example, we create a
Subject
and subscribe it to a cold observable called coldObservable
. We then subscribe to the Subject
twice to turn it into a hot observable. When the first subscriber subscribes, the Subject
starts emitting data from the cold observable, and the second subscriber receives the same data as the first subscriber.2. share or shareReplay
The
share
operator returns a new observable that multicasts the original observable. This means that the observable will only be executed once, regardless of how many subscribers there are. The share
operator will also automatically unsubscribe from the original observable when all subscribers have unsubscribed.import { Observable } from 'rxjs';
import { share } from 'rxjs/operators';
const coldObservable = new Observable(observer => {
console.log('Executing observable');
observer.next(Math.random());
});
const hotObservable = coldObservable.pipe(share());
hotObservable.subscribe(data => console.log(`Subscriber 1: ${data}`));
hotObservable.subscribe(data => console.log(`Subscriber 2: ${data}`));
The
shareReplay
operator is similar to the share
operator, but it also caches the last emitted value and replays it to new subscribers. This means that new (late) subscribers will receive the most recent data, even if they subscribed after the data was emitted.Both the
share
and shareReplay
operators are useful for turning cold observables into hot observables. The share
operator is useful for sharing data between subscribers, while the shareReplay
operator is useful for ensuring that new subscribers receive the most recent data.Conclusion
In conclusion, hot and cold observables are both powerful tools in the world of reactive programming. Hot observables emit data continuously, regardless of whether or not there are any subscribers, while cold observables emit data only when there is a subscriber. Choosing between the two depends on the specific use case. Hot observables are useful when data needs to be shared between multiple subscribers, while cold observables are useful when data is static or expensive to generate.