Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

rxjs - What is the difference between Rx.Observable subscribe and forEach

After creating an Observable like so

var source = Rx.Observable.create(function(observer) {...});

What is the difference between subscribe

source.subscribe(function(x) {});

and forEach

source.forEach(function(x) {});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the ES7 spec, which RxJS 5.0 follows (but RxJS 4.0 does not), the two are NOT the same.

subscribe

public subscribe(observerOrNext: Observer | Function, error: Function, complete: Function): Subscription

Observable.subscribe is where you will do most of your true Observable handling. It returns a subscription token, which you can use to cancel your subscription. This is important when you do not know the duration of the events/sequence you have subscribed to, or if you may need to stop listening before a known duration.

forEach

public forEach(next: Function, PromiseCtor?: PromiseConstructor): Promise

Observable.forEach returns a promise that will either resolve or reject when the Observable completes or errors. It is intended to clarify situations where you are processing an observable sequence of bounded/finite duration in a more 'synchronous' manner, such as collating all the incoming values and then presenting once, by handling the promise.

Effectively, you can act on each value, as well as error and completion events either way. So the most significant functional difference is the inability to cancel a promise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...