forkJoin.js 2.6 KB

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