Skip to content

Instantly share code, notes, and snippets.

@ThomasBurleson
Last active October 11, 2020 17:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ThomasBurleson/3ddac22ec66649c8100e66db06711bc4 to your computer and use it in GitHub Desktop.
Save ThomasBurleson/3ddac22ec66649c8100e66db06711bc4 to your computer and use it in GitHub Desktop.
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