Rx.Observable subscribe 和 forEach 有什么区别 [英] What is the difference between Rx.Observable subscribe and forEach

查看:38
本文介绍了Rx.Observable subscribe 和 forEach 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像这样创建一个 Observable 之后

After creating an Observable like so

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

订阅

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

forEach

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

推荐答案

ES7 规范中,RxJS 5.0 如下(但 RxJS 4.0 没有),两者不一样.

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

订阅

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

Observable.subscribe 是您进行大部分真正 Observable 处理的地方.它返回一个订阅令牌,您可以使用它来取消订阅.当您不知道订阅的事件/序列的持续时间,或者您可能需要在已知持续时间之前停止收听时,这一点很重要.

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 返回一个承诺,当 Observable 完成或出错时,该承诺将解决或拒绝.它旨在阐明您以更同步"的方式处理有界/有限持续时间的可观察序列的情况,例如整理所有传入值,然后通过处理承诺呈现一次.

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.

这篇关于Rx.Observable subscribe 和 forEach 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆