windowTime.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Subject } from '../Subject';
  2. import { asyncScheduler } from '../scheduler/async';
  3. import { Subscription } from '../Subscription';
  4. import { operate } from '../util/lift';
  5. import { createOperatorSubscriber } from './OperatorSubscriber';
  6. import { arrRemove } from '../util/arrRemove';
  7. import { popScheduler } from '../util/args';
  8. import { executeSchedule } from '../util/executeSchedule';
  9. export function windowTime(windowTimeSpan) {
  10. var _a, _b;
  11. var otherArgs = [];
  12. for (var _i = 1; _i < arguments.length; _i++) {
  13. otherArgs[_i - 1] = arguments[_i];
  14. }
  15. var scheduler = (_a = popScheduler(otherArgs)) !== null && _a !== void 0 ? _a : asyncScheduler;
  16. var windowCreationInterval = (_b = otherArgs[0]) !== null && _b !== void 0 ? _b : null;
  17. var maxWindowSize = otherArgs[1] || Infinity;
  18. return operate(function (source, subscriber) {
  19. var windowRecords = [];
  20. var restartOnClose = false;
  21. var closeWindow = function (record) {
  22. var window = record.window, subs = record.subs;
  23. window.complete();
  24. subs.unsubscribe();
  25. arrRemove(windowRecords, record);
  26. restartOnClose && startWindow();
  27. };
  28. var startWindow = function () {
  29. if (windowRecords) {
  30. var subs = new Subscription();
  31. subscriber.add(subs);
  32. var window_1 = new Subject();
  33. var record_1 = {
  34. window: window_1,
  35. subs: subs,
  36. seen: 0,
  37. };
  38. windowRecords.push(record_1);
  39. subscriber.next(window_1.asObservable());
  40. executeSchedule(subs, scheduler, function () { return closeWindow(record_1); }, windowTimeSpan);
  41. }
  42. };
  43. if (windowCreationInterval !== null && windowCreationInterval >= 0) {
  44. executeSchedule(subscriber, scheduler, startWindow, windowCreationInterval, true);
  45. }
  46. else {
  47. restartOnClose = true;
  48. }
  49. startWindow();
  50. var loop = function (cb) { return windowRecords.slice().forEach(cb); };
  51. var terminate = function (cb) {
  52. loop(function (_a) {
  53. var window = _a.window;
  54. return cb(window);
  55. });
  56. cb(subscriber);
  57. subscriber.unsubscribe();
  58. };
  59. source.subscribe(createOperatorSubscriber(subscriber, function (value) {
  60. loop(function (record) {
  61. record.window.next(value);
  62. maxWindowSize <= ++record.seen && closeWindow(record);
  63. });
  64. }, function () { return terminate(function (consumer) { return consumer.complete(); }); }, function (err) { return terminate(function (consumer) { return consumer.error(err); }); }));
  65. return function () {
  66. windowRecords = null;
  67. };
  68. });
  69. }
  70. //# sourceMappingURL=windowTime.js.map