Rx.Observable subscribe和forEach有什么区别

时间:2015-12-30 16:22:24

标签: rxjs

创建像这样的Observable

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

订阅

之间有什么区别?
source.subscribe(function(x) {});

forEach

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

3 个答案:

答案 0 :(得分:56)

Console result中,ES7 spec跟随(但RxJS 4.0没有),两者并不相同。

<强>订阅

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

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

<强>的forEach

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

Observable.forEach返回一个承诺,该承诺将在Observable完成或错误时解析或拒绝。它旨在阐明您以更“同步”的方式处理可观察的有界/有限持续时间序列的情况,例如整理所有传入的值,然后通过处理承诺呈现一次。

实际上,无论哪种方式,您都可以对每个值以及错误和完成事件采取行动。因此,最重要的功能差异是无法取消承诺。

答案 1 :(得分:1)

我只是查看可用的最新代码,从技术上讲,foreach的代码实际上是在RxScala,RxJS和RxJava中调用subscribe。它似乎并没有太大的不同。他们现在有一个返回类型,允许用户有办法停止订阅或类似。

当我处理RxJava早期版本时,subscribe有一个订阅返回,而forEach只是一个空白。由于这些变化,您可能会看到一些不同的答案。

/**
 * Subscribes to the [[Observable]] and receives notifications for each element.
 *
 * Alias to `subscribe(T => Unit)`.
 *
 * $noDefaultScheduler
 *  
 * @param onNext function to execute for each item.
 * @throws java.lang.IllegalArgumentException if `onNext` is null
 * @throws rx.exceptions.OnErrorNotImplementedException if the [[Observable]] tries to call `onError`
 * @since 0.19
 * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a>
 */
def foreach(onNext: T => Unit): Unit = {
    asJavaObservable.subscribe(onNext)
 }

def subscribe(onNext: T => Unit): Subscription = {
    asJavaObservable.subscribe(scalaFunction1ProducingUnitToAction1(onNext))
}

/**
 *  Subscribes an o to the observable sequence.
 *  @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
 *  @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
 *  @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
 *  @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
 */
observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) {
  return this._subscribe(typeof oOrOnNext === 'object' ?
    oOrOnNext :
    observerCreate(oOrOnNext, onError, onCompleted));
};

/**
 * Subscribes to the {@link Observable} and receives notifications for each element.
 * <p>
 * Alias to {@link #subscribe(Action1)}
 * <dl>
 *  <dt><b>Scheduler:</b></dt>
 *  <dd>{@code forEach} does not operate by default on a particular {@link Scheduler}.</dd>
 * </dl>
 * 
 * @param onNext
 *            {@link Action1} to execute for each item.
 * @throws IllegalArgumentException
 *             if {@code onNext} is null
 * @throws OnErrorNotImplementedException
 *             if the Observable calls {@code onError}
 * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a>
 */
public final void forEach(final Action1<? super T> onNext) {
    subscribe(onNext);
}

public final Disposable forEach(Consumer<? super T> onNext) {
    return subscribe(onNext);
}

答案 2 :(得分:-5)

observable.subscribe(...)observable.forEach(...)完全相同  正如用户3743222在他的answer

中提到的那样

来自Rx文档:

为可观察序列订阅观察者。

Rx.Observable.prototype.subscribe([observer] | [onNext], [onError], [onCompleted])

Rx.Observable.prototype.forEach([observer] | [onNext], [onError], [onCompleted])

有关详细信息,请参见完整的documentation