Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Why is RxJS::defer() important!

Quite simply, because Observables can encapsulate many different types of sources and those sources don't necessarily have to obey that interface. Some like Promises always attempt to eagerly compete.

Consider:

const promise = $.get('https://www.google.com');

The promise in this case is already executing before any handlers have been connected. If we want this to act more like an Observable then we need some way of deferring the creation of the promise until there is a subscription.

Hence we use defer to create a block that only gets executed when the resulting Observable is subscribed to.

Observable.defer(() => $.get('https://www.google.com'));

The above will not create the Promise until the Observable gets subscribed to and will thus behaves much more in line with the standard Observable interface.

Thanks to @PaulPDaniels on StackOverflow Answer

It's also worth pointing out that the Observable returned by defer() will run the provided factory function every time it is subscribed to. These are known as COLD observables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment