In RxJS, Observables are used to model asynchronous data streams. They can be classified into two types based on their behavior: Hot Observables and Cold Observables. Let’s dive into the differences between the two and provide some examples.
**Cold Observables**
A cold Observable is an Observable that does not start producing values until it has a subscriber. It generates new data or re-calculates its values for each subscriber. Each subscriber will have an independent instance of the Observable, hence they will have their own execution context and will receive unique values of the stream. Once the Observable completes or an error occurs, it’s unable to be reused for further subscriptions.
Some examples of cold Observables are:
1. Reading a file from disk
2. Making an HTTP request
3. Generating random numbers
Here’s a simple example of a cold Observable that generates random numbers:
import { Observable } from 'rxjs';
const cold$ = new Observable(subscriber => {
subscriber.next(Math.random());
subscriber.complete();
});
// Each subscriber will receive a different random number.
cold$.subscribe(val => console.log('First Subscriber:', val));
cold$.subscribe(val => console.log('Second Subscriber:', val));
**Hot Observables**
A hot Observable is an Observable that can start producing values without any subscribers. Where cold observables generate new values per subscription, hot observables can share their execution context among multiple subscribers. Additionally, subscribers can join an ongoing stream, which may cause them to miss values that have been already emitted.
Some examples of hot Observables are:
1. Mouse clicks
2. Key presses
3. WebSockets
Here’s an example of a hot Observable that emits mouse clicks:
import { Observable } from 'rxjs';
const clicks$ = new Observable(subscriber => {
document.addEventListener('click', (e) => subscriber.next(e));
});
// Both subscribers receive the same mouse click events.
clicks$.subscribe(e => console.log('First Subscriber:', e));
setTimeout(() => {
clicks$.subscribe(e => console.log('Second Subscriber:', e));
}, 2000);
In summary, cold and hot Observables differ in the way they produce and share values with their subscribers. Cold Observables don’t produce values until a subscription occurs, and produce new values for each subscriber. Hot Observables, on the other hand, produce values independently of subscriptions, and share the same execution context with multiple subscribers.