forkJoin.js 2.7 KB

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