What's the difference between two observables if they are created by deferral?

For example, var interval = Rx.Observable.interval(1000); interval.subscribe(x => console.log(x));

A also var deferred = Rx.Observable.defer(()=> return interval); deferred.subscribe(x=> console.log(x));

seems to be doing the same. Observables seem to be "deferred" by default. What's being put aside for?

+1


source to share


1 answer


defer

takes a parameter function that returns an observable. The operator itself returns an observable, as most operators do. When an defer

observable subscribes , it executes the parameter function, gets the observable returned by the function, and subscribes to the observable, and passes the values ​​from the observable downstream.

This is useful if you want to defer the creation of the observable returned by the function until defer

the subscription time. defer

Doesn't make a lot of difference in your example , but it's useful, for example when you have a callback that makes some kind of API call and returns an observable / promise, but you don't want to trigger the API call immediately.



Example is better than a lot of words, and you will find some in the matter of such of SO, for example RxJS and retarding functions setState React to subscribe , How to start the second monitored * only * after * first * fully done rxjs , and Rx.js awaits completion callback .

+1


source







All Articles