Hot vs Cold Observables

TL;DR: You want a HOT observable when you don’t want to create your producer over and over again.

COLD is when your observable creates the producer

// COLD
var cold = new Observable((observer) => {
var producer = new Producer();
// have observer listen to producer here
});

HOT is when your observable closes over the producer

// HOT
var producer = new Producer();
var hot = new Observable((observer) => {
// have observer listen to producer here
});

Getting deeper into what’s going on…

Observables are just functions!

What’s a “Producer”?

Cold Observables: Producers created *inside*

const source = new Observable((observer) => {
const socket = new WebSocket('ws://someurl');
socket.addEventListener('message', (e) => observer.next(e));
return () => socket.close();
});

Hot Observables: Producers created *outside*

const socket = new WebSocket('ws://someurl');const source = new Observable((observer) => {
socket.addEventListener('message', (e) => observer.next(e));
});

Why Make A “Hot” Observable?

source.filter(x => x % 2 === 0)
.subscribe(x => console.log('even', x));
source.filter(x => x % 2 === 1)
.subscribe(x => console.log('odd', x));

Rx Subjects

Making A Cold Observable Hot

function makeHot(cold) {
const subject = new Subject();
cold.subscribe(subject);
return new Observable((observer) => subject.subscribe(observer));
}
function makeHotRefCounted(cold) {
const subject = new Subject();
const mainSub = cold.subscribe(subject);
let refs = 0;
return new Observable((observer) => {
refs++;
let sub = subject.subscribe(observer);
return () => {
refs--;
if (refs === 0) mainSub.unsubscribe();
sub.unsubscribe();
};
});
}

In RxJS, Use `publish()` or `share()`

The “Warm” Observable

“Hot” And “Cold” Are All About The Producer

NOTES

RxJS Lead. Views are my own

RxJS Lead. Views are my own