Observable.fromPromise cold or hot?

Julia Passynkova
Angular In Depth
Published in
2 min readMay 8, 2017

AngularInDepth is moving away from Medium. More recent articles are hosted on the new platform inDepth.dev. Thanks for being part of indepth movement!

In my past years I used a lot of Promises and as you probably know a promise will start running as soon as you create it. On other hand, observables are cold and it means till you subscribe — nothing will run.

Let’s see the difference.

So this code with Promise will run immediately:

let p = new Promise((res)=> {
alert('Promise1');
res();
});

and this code with Observable won’t do anything till you subscribe:

Rx.Observable.of(1).do(x=>alert('Observable'))

to make it show the alert you need subscribe:

Rx.Observable.of(1).do(x=>alert('Observable'))
.subscribe();

I moved to Angular world with Observables and so used to idea of cold Observables so Observable.fromPromise behaviour really surprised me at the beginning.

What to do you think will happen in the follow code?

let obs1$ = Rx.Observable.fromPromise(new Promise((res)=> {
alert('Promise1');
res();
}));

We use observables, yes? But we will have two alerts immediately and this is what I actually recently got as a defect.

How to make it cold?

I found several ways to postpose the promise executing inside Observable.fromPromise and make it more align with cold Observable paradigm.

SwitchMap operator

Wrapping Rx.Observable.fromPromise into switchMap and chaining it with Observable.of makes the promise “cold”.

let obs1$ = Rx.Observable.of(1)
.switchMap(x=>Rx.Observable.fromPromise(new Promise((res)=> {
alert('Promise1');
res();
})));

Defer operator

I recently discovered defer operator and it worked magically for Rx.Observable.fromPromise. This is what documentation says about defer:

Defer: Creates an Observable that, on subscribe, calls an Observable factory to make an Observable for each new Observer.

This code also won’t run till subscribe is called.

let obs1$ = Rx.Observable.defer(()=>
Rx.Observable.fromPromise(new Promise((res)=> {
alert('Promise1');
res();
})));

So, now you know how to make Observable.fromPromise “cold”.

--

--

Julia Passynkova
Angular In Depth

Front-End developer working as an independent contractor with Angular and React in Toronto, Canada.