race.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { isArray } from '../util/isArray';
  2. import { ArrayObservable } from '../observable/ArrayObservable';
  3. import { OuterSubscriber } from '../OuterSubscriber';
  4. import { subscribeToResult } from '../util/subscribeToResult';
  5. export function race(...observables) {
  6. // if the only argument is an array, it was most likely called with
  7. // `race([obs1, obs2, ...])`
  8. if (observables.length === 1) {
  9. if (isArray(observables[0])) {
  10. observables = observables[0];
  11. }
  12. else {
  13. return observables[0];
  14. }
  15. }
  16. return new ArrayObservable(observables).lift(new RaceOperator());
  17. }
  18. export class RaceOperator {
  19. call(subscriber, source) {
  20. return source.subscribe(new RaceSubscriber(subscriber));
  21. }
  22. }
  23. /**
  24. * We need this JSDoc comment for affecting ESDoc.
  25. * @ignore
  26. * @extends {Ignored}
  27. */
  28. export class RaceSubscriber extends OuterSubscriber {
  29. constructor(destination) {
  30. super(destination);
  31. this.hasFirst = false;
  32. this.observables = [];
  33. this.subscriptions = [];
  34. }
  35. _next(observable) {
  36. this.observables.push(observable);
  37. }
  38. _complete() {
  39. const observables = this.observables;
  40. const len = observables.length;
  41. if (len === 0) {
  42. this.destination.complete();
  43. }
  44. else {
  45. for (let i = 0; i < len && !this.hasFirst; i++) {
  46. let observable = observables[i];
  47. let subscription = subscribeToResult(this, observable, observable, i);
  48. if (this.subscriptions) {
  49. this.subscriptions.push(subscription);
  50. }
  51. this.add(subscription);
  52. }
  53. this.observables = null;
  54. }
  55. }
  56. notifyNext(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
  57. if (!this.hasFirst) {
  58. this.hasFirst = true;
  59. for (let i = 0; i < this.subscriptions.length; i++) {
  60. if (i !== outerIndex) {
  61. let subscription = this.subscriptions[i];
  62. subscription.unsubscribe();
  63. this.remove(subscription);
  64. }
  65. }
  66. this.subscriptions = null;
  67. }
  68. this.destination.next(innerValue);
  69. }
  70. }
  71. //# sourceMappingURL=race.js.map