Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS, understanding defer

Tags:

rxjs

I searched for the usage of defer in RxJS but still I don't understand why and when to use it.

As I understand neither Observable methods is fired before someone subscribes to it.

If that's the case then why do we need to wrap an Observable method with defer?

An example

I'm still wondering why it wrapped Observable with defer? Does it make any difference?

var source = Rx.Observable.defer(function () {   return Rx.Observable.return(42); });  var subscription = source.subscribe(   function (x) { console.log('Next: ' + x); },   function (err) { console.log('Error: ' + err); },   function () { console.log('Completed'); } ); 
like image 850
Expert wanna be Avatar asked Aug 04 '16 10:08

Expert wanna be


People also ask

What is defer in RXJS?

defer allows you to create an Observable only when the Observer subscribes. It waits until an Observer subscribes to it, calls the given factory function to get an Observable -- where a factory function typically generates a new Observable -- and subscribes the Observer to this Observable.

What is defer in Angular?

defer() allows you to create a promise object which you might want to return to the function that called your login function.

What is of operator in RXJS?

The of Operator is a creation Operator. Creation Operators are functions that create an Observable stream from a source. The of Operator will create an Observable that emits a variable amount of values in sequence, followed by a Completion notification.


1 Answers

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:

var 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.

like image 69
paulpdaniels Avatar answered Sep 17 '22 17:09

paulpdaniels