Hot and cold Observable
Producer
A producer is the source of values for your observable. It could be a web socket, it could be DOM events, it could be an iterator, or something looping over an array. Basically, it’s anything you’re using to get values and pass them to `observer.next(value)`.
Cold observable
An observable is “cold” if its underlying producer is created and activated during subscription. This means, that if observables are functions, then the producer is created and activated by calling that function.
const source = new Observable((observer) => {
const socket = new WebSocket('ws://someurl');
socket.addEventListener('message', (e) => observer.next(e));
return () => socket.close();
});
In this case for every observer is created new instance of WebSocket.
Hot observable
An observable is “hot” if its underlying producer is either created or activated outside of subscription.¹
const socket = new WebSocket('ws://someurl');
const source = new Observable((observer) => {
socket.addEventListener('message', (e) => observer.next(e));
});
Now anything that subscribes to `source` will share the same WebSocket instance. It will effectively multicast to all subscribers now. But we have a little problem: We’re no longer carrying the logic to teardown the socket with our observable. That means that things like errors and completions, as well as unsubscribe, will no longer close the socket for us. So what we really want is to make our “cold” observable “hot”.
Making A Cold Observable Hot
In RxJS 5, the operator `share()` makes a hot, refCounted observable that can be retried on failure, or repeated on success.
const source = new Observable((observer) => {
const socket = new FakeWebSocket('ws://someurl');
socket.addEventListener('message', (e) => observer.next(e));
return () => socket.close();
});
// magic here.
const hot = source.share();
hot.subscribe(data => {});
Source: https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339