Warm tip: This article is reproduced from stackoverflow.com, please click
rxjs

Rxjs, understanding defer

发布于 2020-04-11 22:23:59

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?

Questioner
Expert wanna be
Viewed
46
paulpdaniels 2016-08-04 23:17

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.