groupBy.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { Observable } from '../Observable';
  2. import { innerFrom } from '../observable/innerFrom';
  3. import { Subject } from '../Subject';
  4. import { operate } from '../util/lift';
  5. import { createOperatorSubscriber, OperatorSubscriber } from './OperatorSubscriber';
  6. export function groupBy(keySelector, elementOrOptions, duration, connector) {
  7. return operate((source, subscriber) => {
  8. let element;
  9. if (!elementOrOptions || typeof elementOrOptions === 'function') {
  10. element = elementOrOptions;
  11. }
  12. else {
  13. ({ duration, element, connector } = elementOrOptions);
  14. }
  15. const groups = new Map();
  16. const notify = (cb) => {
  17. groups.forEach(cb);
  18. cb(subscriber);
  19. };
  20. const handleError = (err) => notify((consumer) => consumer.error(err));
  21. let activeGroups = 0;
  22. let teardownAttempted = false;
  23. const groupBySourceSubscriber = new OperatorSubscriber(subscriber, (value) => {
  24. try {
  25. const key = keySelector(value);
  26. let group = groups.get(key);
  27. if (!group) {
  28. groups.set(key, (group = connector ? connector() : new Subject()));
  29. const grouped = createGroupedObservable(key, group);
  30. subscriber.next(grouped);
  31. if (duration) {
  32. const durationSubscriber = createOperatorSubscriber(group, () => {
  33. group.complete();
  34. durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
  35. }, undefined, undefined, () => groups.delete(key));
  36. groupBySourceSubscriber.add(innerFrom(duration(grouped)).subscribe(durationSubscriber));
  37. }
  38. }
  39. group.next(element ? element(value) : value);
  40. }
  41. catch (err) {
  42. handleError(err);
  43. }
  44. }, () => notify((consumer) => consumer.complete()), handleError, () => groups.clear(), () => {
  45. teardownAttempted = true;
  46. return activeGroups === 0;
  47. });
  48. source.subscribe(groupBySourceSubscriber);
  49. function createGroupedObservable(key, groupSubject) {
  50. const result = new Observable((groupSubscriber) => {
  51. activeGroups++;
  52. const innerSub = groupSubject.subscribe(groupSubscriber);
  53. return () => {
  54. innerSub.unsubscribe();
  55. --activeGroups === 0 && teardownAttempted && groupBySourceSubscriber.unsubscribe();
  56. };
  57. });
  58. result.key = key;
  59. return result;
  60. }
  61. });
  62. }
  63. //# sourceMappingURL=groupBy.js.map