forkJoin.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /** PURE_IMPORTS_START _Observable,_util_isArray,_operators_map,_util_isObject,_from PURE_IMPORTS_END */
  2. import { Observable } from '../Observable';
  3. import { isArray } from '../util/isArray';
  4. import { map } from '../operators/map';
  5. import { isObject } from '../util/isObject';
  6. import { from } from './from';
  7. export function forkJoin() {
  8. var sources = [];
  9. for (var _i = 0; _i < arguments.length; _i++) {
  10. sources[_i] = arguments[_i];
  11. }
  12. if (sources.length === 1) {
  13. var first_1 = sources[0];
  14. if (isArray(first_1)) {
  15. return forkJoinInternal(first_1, null);
  16. }
  17. if (isObject(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) {
  18. var keys = Object.keys(first_1);
  19. return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys);
  20. }
  21. }
  22. if (typeof sources[sources.length - 1] === 'function') {
  23. var resultSelector_1 = sources.pop();
  24. sources = (sources.length === 1 && isArray(sources[0])) ? sources[0] : sources;
  25. return forkJoinInternal(sources, null).pipe(map(function (args) { return resultSelector_1.apply(void 0, args); }));
  26. }
  27. return forkJoinInternal(sources, null);
  28. }
  29. function forkJoinInternal(sources, keys) {
  30. return new Observable(function (subscriber) {
  31. var len = sources.length;
  32. if (len === 0) {
  33. subscriber.complete();
  34. return;
  35. }
  36. var values = new Array(len);
  37. var completed = 0;
  38. var emitted = 0;
  39. var _loop_1 = function (i) {
  40. var source = from(sources[i]);
  41. var hasValue = false;
  42. subscriber.add(source.subscribe({
  43. next: function (value) {
  44. if (!hasValue) {
  45. hasValue = true;
  46. emitted++;
  47. }
  48. values[i] = value;
  49. },
  50. error: function (err) { return subscriber.error(err); },
  51. complete: function () {
  52. completed++;
  53. if (completed === len || !hasValue) {
  54. if (emitted === len) {
  55. subscriber.next(keys ?
  56. keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) :
  57. values);
  58. }
  59. subscriber.complete();
  60. }
  61. }
  62. }));
  63. };
  64. for (var i = 0; i < len; i++) {
  65. _loop_1(i);
  66. }
  67. });
  68. }
  69. //# sourceMappingURL=forkJoin.js.map