I searched for usage defer in Reactive, but still I don't understand why and when use the defer method.
As I understand all Observable method will not be fired until it subscribed, then, why we need to wrap the observable method with defer method?
Please advice me, and would be very appreciated if giving me with example.
[Updated]
Now I understood.
In reactive documentation, I saw this example,
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'); } );
And I was wondered,
why it wrapped Observable method with defer? How it will act differently?
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.
@AlexPineda not sure what you mean.
defer
already understandsPromises
so it already implicitly handles them, so you wouldn't needfromPromise
unless you wanted its use to be explicit.I think what he means is that if you do
fromPromise(promise)
thepromise
being passed tofromPromise
is already executing and thefromPromise
just returns that promise in an Observable wrapper. By usingdefer
, the promise will not start executing until we subscribe.