What's the difference between two Observables if one is created by defer?

走远了吗. 提交于 2019-12-11 13:17:59

问题


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.



来源:https://stackoverflow.com/questions/37447469/whats-the-difference-between-two-observables-if-one-is-created-by-defer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!