UNPKG

@reactivex/rxjs

Version:

Reactive Extensions for modern JavaScript

86 lines 2.98 kB
import { isArray } from '../util/isArray'; import { ArrayObservable } from '../observable/ArrayObservable'; import { OuterSubscriber } from '../OuterSubscriber'; import { subscribeToResult } from '../util/subscribeToResult'; /** * Returns an Observable that mirrors the first source Observable to emit an item * from the combination of this Observable and supplied Observables * @param {...Observables} ...observables sources used to race for which Observable emits first. * @return {Observable} an Observable that mirrors the output of the first Observable to emit an item. * @method race * @owner Observable */ export function race(...observables) { // if the only argument is an array, it was most likely called with // `pair([obs1, obs2, ...])` if (observables.length === 1 && isArray(observables[0])) { observables = observables[0]; } observables.unshift(this); return raceStatic.apply(this, observables); } export function raceStatic(...observables) { // if the only argument is an array, it was most likely called with // `pair([obs1, obs2, ...])` if (observables.length === 1) { if (isArray(observables[0])) { observables = observables[0]; } else { return observables[0]; } } return new ArrayObservable(observables).lift(new RaceOperator()); } export class RaceOperator { call(subscriber, source) { return source._subscribe(new RaceSubscriber(subscriber)); } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export class RaceSubscriber extends OuterSubscriber { constructor(destination) { super(destination); this.hasFirst = false; this.observables = []; this.subscriptions = []; } _next(observable) { this.observables.push(observable); } _complete() { const observables = this.observables; const len = observables.length; if (len === 0) { this.destination.complete(); } else { for (let i = 0; i < len; i++) { let observable = observables[i]; let subscription = subscribeToResult(this, observable, observable, i); this.subscriptions.push(subscription); this.add(subscription); } this.observables = null; } } notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) { if (!this.hasFirst) { this.hasFirst = true; for (let i = 0; i < this.subscriptions.length; i++) { if (i !== outerIndex) { let subscription = this.subscriptions[i]; subscription.unsubscribe(); this.remove(subscription); } } this.subscriptions = null; } this.destination.next(innerValue); } } //# sourceMappingURL=race.js.map