es6/operator/race.js
import { isArray } from '../util/isArray';
import { ArrayObservable } from '../observable/ArrayObservable';
import { OuterSubscriber } from '../OuterSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
/* tslint:enable:max-line-length */
/**
* 返回 Observable,该 Observable 是源 Observable 和提供的 Observables 的组合中
* 第一个发出项的 Observable 的镜像。
* @param {...Observables} ...observables 用于竞争的 Observables 源,以比试哪个 Observable 会首先发出项。
* @return {Observable} 该 Observable 是第一个发出项的 Observable 输出镜像。
* @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];
}
return this.lift.call(raceStatic(this, ...observables));
}
export function raceStatic(...observables) {
// if the only argument is an array, it was most likely called with
// `race([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 && !this.hasFirst; i++) {
let observable = observables[i];
let subscription = subscribeToResult(this, observable, observable, i);
if (this.subscriptions) {
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