Hot vs Cold Observables

Dhanashekhar Tontanahal
2 min readFeb 24, 2021
Hot vs Cold :-)

Hot Observables can have multiple subscriptions where as cold observables can have single subscription.

Cold Observables don’t actually create the value until they are subscribed to.

So If you have more than one subscriber your cold observable is going to be instantiated every time it is subscribed to, which is costly.

Output console is like below

You see that :-)

This ends up being costly when we have multiple subscribers, because the cold observable(s) are actually creating the value when they are subscribed to.

What if we can have a mechanism which can help us cache the value of observables first time when they emit after they were subscribed to ?

Sounds useful right ?

Cold to hot

Rxjs provides some useful operators like shareReplay(numberOfReplays)

import {shareReplay } from ‘rxjs/operators’;

Gives the output as below

With this shareReplay(1) we communicate to rxjs that boss help me cache the last 1 value created by the first subscription.

What if we have shareReplay(2) ?

See that !

The last 2 emitted values of the first subscription are cached and returned to the subscribers who are lately subscribed to the observable.

Hence the latecomers are respected with the same dignity as first subscriber .

:-)

So we looked at converting cold observables to hot observables using the pipe and passing the shareReplay(cacheLastNumofValues) operator.

So shareReplay() gives access to previously emitted values for all the late subscribers to an observable

You generally want take the benefit of shareReplay when you have side-effects or costly computations that you donot wish to be executed for every late subscriber or amongst multiple subscribers.

Thank you for your patience and consideration my beautiful people.

--

--