What's the difference between two Observables

2019-08-15 13:33发布

问题:

For instance, var interval = Rx.Observable.interval(1000); interval.subscribe(x => console.log(x)); And var deferred = Rx.Observable.defer(()=> return interval); deferred.subscribe(x=> console.log(x)); seem to do the same thing. It seems to that observables are by default "deferred". What is defer useful for?

回答1:

defer takes a parameter function which returns an observable. The operator itself returns an observable, as most operators do. When that defer observable is subscribed to, it executes the parameter function, get the observable returned by the function and subscribes to that observable, and pass on the values from that observable down the stream.

That is useful, when you want to defer the creation of the observable returned by the function to defer subscription time. In your example, defer does not bring much value, but it is useful for instance when you have a callback which executes some API call and returns an observable/promise but you don't want to execute the API call straight away.

Examples are better than many words and you will find some in similar question on SO, for instance RxJS and React's setState - delay function execution until subscription, How to start second observable *only* after first is *completely* done in rxjs, and Rx.js wait for callback to complete.