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'); } );
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.
defer() allows you to create a promise object which you might want to return to the function that called your login function.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With