What is the difference between Rx.Observable subscribe and forEach

前端 未结 2 412
南旧
南旧 2020-12-05 01:34

After creating an Observable like so

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

What is the difference between su

2条回答
  •  攒了一身酷
    2020-12-05 02:12

    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.

提交回复
热议问题