What is the difference between Rx.Observable subscribe and forEach

前端 未结 2 413
南旧
南旧 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:18

    I just review the latest code available, technically the code of foreach is actually calling subscribe in RxScala, RxJS, and RxJava. It doesn't seems a big different. They now have a return type allowing user to have an way for stopping a subscription or similar.

    When I work on the RxJava earlier version, the subscribe has a subscription return, and forEach is just a void. Which you may see some different answer due to the changes.

    /**
     * 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 ReactiveX operators documentation: Subscribe
     */
    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.
     * 

    * Alias to {@link #subscribe(Action1)} *

    *
    Scheduler:
    *
    {@code forEach} does not operate by default on a particular {@link Scheduler}.
    *
    * * @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 ReactiveX operators documentation: Subscribe */ public final void forEach(final Action1 onNext) { subscribe(onNext); } public final Disposable forEach(Consumer onNext) { return subscribe(onNext); }

提交回复
热议问题