Debian Codegraph @

node/rxjs/src/internal/operators/groupBy.ts

raw
1 import { Observable } from '../Observable';
2 import { innerFrom } from '../observable/innerFrom';
3 import { Subject } from '../Subject';
4 import { ObservableInput, Observer, OperatorFunction, SubjectLike } from '../types';
5 import { operate } from '../util/lift';
6 import { createOperatorSubscriber, OperatorSubscriber } from './OperatorSubscriber';
7
8 export interface BasicGroupByOptions<K, T> {
9 element?: undefined;
10 duration?: (grouped: GroupedObservable<K, T>) => ObservableInput<any>;
11 connector?: () => SubjectLike<T>;
12 }
13
14 export interface GroupByOptionsWithElement<K, E, T> {
15 element: (value: T) => E;
16 duration?: (grouped: GroupedObservable<K, E>) => ObservableInput<any>;
17 connector?: () => SubjectLike<E>;
18 }
19
20 export function groupBy<T, K>(key: (value: T) => K, options: BasicGroupByOptions<K, T>): OperatorFunction<T, GroupedObservable<K, T>>;
21
22 export function groupBy<T, K, E>(
23 key: (value: T) => K,
24 options: GroupByOptionsWithElement<K, E, T>
25 ): OperatorFunction<T, GroupedObservable<K, E>>;
26
27 export function groupBy<T, K extends T>(
28 key: (value: T) => value is K
29 ): OperatorFunction<T, GroupedObservable<true, K> | GroupedObservable<false, Exclude<T, K>>>;
30
31 export function groupBy<T, K>(key: (value: T) => K): OperatorFunction<T, GroupedObservable<K, T>>;
32
33 /**
34 * @deprecated use the options parameter instead.
35 */
36 export function groupBy<T, K>(
37 key: (value: T) => K,
38 element: void,
39 duration: (grouped: GroupedObservable<K, T>) => Observable<any>
40 ): OperatorFunction<T, GroupedObservable<K, T>>;
41
42 /**
43 * @deprecated use the options parameter instead.
44 */
45 export function groupBy<T, K, R>(
46 key: (value: T) => K,
47 element?: (value: T) => R,
48 duration?: (grouped: GroupedObservable<K, R>) => Observable<any>
49 ): OperatorFunction<T, GroupedObservable<K, R>>;
50
51 /**
52 * Groups the items emitted by an Observable according to a specified criterion,
53 * and emits these grouped items as `GroupedObservables`, one
54 * {@link GroupedObservable} per group.
55 *
56 * ![](groupBy.png)
57 *
58 * When the Observable emits an item, a key is computed for this item with the key function.
59 *
60 * If a {@link GroupedObservable} for this key exists, this {@link GroupedObservable} emits. Otherwise, a new
61 * {@link GroupedObservable} for this key is created and emits.
62 *
63 * A {@link GroupedObservable} represents values belonging to the same group represented by a common key. The common
64 * key is available as the `key` field of a {@link GroupedObservable} instance.
65 *
66 * The elements emitted by {@link GroupedObservable}s are by default the items emitted by the Observable, or elements
67 * returned by the element function.
68 *
69 * ## Examples
70 *
71 * Group objects by `id` and return as array
72 *
73 * ```ts
74 * import { of, groupBy, mergeMap, reduce } from 'rxjs';
75 *
76 * of(
77 * { id: 1, name: 'JavaScript' },
78 * { id: 2, name: 'Parcel' },
79 * { id: 2, name: 'webpack' },
80 * { id: 1, name: 'TypeScript' },
81 * { id: 3, name: 'TSLint' }
82 * ).pipe(
83 * groupBy(p => p.id),
84 * mergeMap(group$ => group$.pipe(reduce((acc, cur) => [...acc, cur], [])))
85 * )
86 * .subscribe(p => console.log(p));
87 *
88 * // displays:
89 * // [{ id: 1, name: 'JavaScript' }, { id: 1, name: 'TypeScript'}]
90 * // [{ id: 2, name: 'Parcel' }, { id: 2, name: 'webpack'}]
91 * // [{ id: 3, name: 'TSLint' }]
92 * ```
93 *
94 * Pivot data on the `id` field
95 *
96 * ```ts
97 * import { of, groupBy, mergeMap, reduce, map } from 'rxjs';
98 *
99 * of(
100 * { id: 1, name: 'JavaScript' },
101 * { id: 2, name: 'Parcel' },
102 * { id: 2, name: 'webpack' },
103 * { id: 1, name: 'TypeScript' },
104 * { id: 3, name: 'TSLint' }
105 * ).pipe(
106 * groupBy(p => p.id, { element: p => p.name }),
107 * mergeMap(group$ => group$.pipe(reduce((acc, cur) => [...acc, cur], [`${ group$.key }`]))),
108 * map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) }))
109 * )
110 * .subscribe(p => console.log(p));
111 *
112 * // displays:
113 * // { id: 1, values: [ 'JavaScript', 'TypeScript' ] }
114 * // { id: 2, values: [ 'Parcel', 'webpack' ] }
115 * // { id: 3, values: [ 'TSLint' ] }
116 * ```
117 *
118 * @param key A function that extracts the key
119 * for each item.
120 * @param element A function that extracts the
121 * return element for each item.
122 * @param duration
123 * A function that returns an Observable to determine how long each group should
124 * exist.
125 * @param connector Factory function to create an
126 * intermediate Subject through which grouped elements are emitted.
127 * @return A function that returns an Observable that emits GroupedObservables,
128 * each of which corresponds to a unique key value and each of which emits
129 * those items from the source Observable that share that key value.
130 *
131 * @deprecated Use the options parameter instead.
132 */
133 export function groupBy<T, K, R>(
134 key: (value: T) => K,
135 element?: (value: T) => R,
136 duration?: (grouped: GroupedObservable<K, R>) => Observable<any>,
137 connector?: () => Subject<R>
138 ): OperatorFunction<T, GroupedObservable<K, R>>;
139
140 // Impl
141 export function groupBy<T, K, R>(
142 keySelector: (value: T) => K,
143 elementOrOptions?: ((value: any) => any) | void | BasicGroupByOptions<K, T> | GroupByOptionsWithElement<K, R, T>,
144 duration?: (grouped: GroupedObservable<any, any>) => ObservableInput<any>,
145 connector?: () => SubjectLike<any>
146 ): OperatorFunction<T, GroupedObservable<K, R>> {
147 return operate((source, subscriber) => {
148 let element: ((value: any) => any) | void;
149 if (!elementOrOptions || typeof elementOrOptions === 'function') {
150 element = elementOrOptions as ((value: any) => any);
151 } else {
152 ({ duration, element, connector } = elementOrOptions);
153 }
154
155 // A lookup for the groups that we have so far.
156 const groups = new Map<K, SubjectLike<any>>();
157
158 // Used for notifying all groups and the subscriber in the same way.
159 const notify = (cb: (group: Observer<any>) => void) => {
160 groups.forEach(cb);
161 cb(subscriber);
162 };
163
164 // Used to handle errors from the source, AND errors that occur during the
165 // next call from the source.
166 const handleError = (err: any) => notify((consumer) => consumer.error(err));
167
168 // The number of actively subscribed groups
169 let activeGroups = 0;
170
171 // Whether or not teardown was attempted on this subscription.
172 let teardownAttempted = false;
173
174 // Capturing a reference to this, because we need a handle to it
175 // in `createGroupedObservable` below. This is what we use to
176 // subscribe to our source observable. This sometimes needs to be unsubscribed
177 // out-of-band with our `subscriber` which is the downstream subscriber, or destination,
178 // in cases where a user unsubscribes from the main resulting subscription, but
179 // still has groups from this subscription subscribed and would expect values from it
180 // Consider: `source.pipe(groupBy(fn), take(2))`.
181 const groupBySourceSubscriber = new OperatorSubscriber(
182 subscriber,
183 (value: T) => {
184 // Because we have to notify all groups of any errors that occur in here,
185 // we have to add our own try/catch to ensure that those errors are propagated.
186 // OperatorSubscriber will only send the error to the main subscriber.
187 try {
188 const key = keySelector(value);
189
190 let group = groups.get(key);
191 if (!group) {
192 // Create our group subject
193 groups.set(key, (group = connector ? connector() : new Subject<any>()));
194
195 // Emit the grouped observable. Note that we can't do a simple `asObservable()` here,
196 // because the grouped observable has special semantics around reference counting
197 // to ensure we don't sever our connection to the source prematurely.
198 const grouped = createGroupedObservable(key, group);
199 subscriber.next(grouped);
200
201 if (duration) {
202 const durationSubscriber = createOperatorSubscriber(
203 // Providing the group here ensures that it is disposed of -- via `unsubscribe` --
204 // when the duration subscription is torn down. That is important, because then
205 // if someone holds a handle to the grouped observable and tries to subscribe to it
206 // after the connection to the source has been severed, they will get an
207 // `ObjectUnsubscribedError` and know they can't possibly get any notifications.
208 group as any,
209 () => {
210 // Our duration notified! We can complete the group.
211 // The group will be removed from the map in the finalization phase.
212 group!.complete();
213 durationSubscriber?.unsubscribe();
214 },
215 // Completions are also sent to the group, but just the group.
216 undefined,
217 // Errors on the duration subscriber are sent to the group
218 // but only the group. They are not sent to the main subscription.
219 undefined,
220 // Finalization: Remove this group from our map.
221 () => groups.delete(key)
222 );
223
224 // Start our duration notifier.
225 groupBySourceSubscriber.add(innerFrom(duration(grouped)).subscribe(durationSubscriber));
226 }
227 }
228
229 // Send the value to our group.
230 group.next(element ? element(value) : value);
231 } catch (err) {
232 handleError(err);
233 }
234 },
235 // Source completes.
236 () => notify((consumer) => consumer.complete()),
237 // Error from the source.
238 handleError,
239 // Free up memory.
240 // When the source subscription is _finally_ torn down, release the subjects and keys
241 // in our groups Map, they may be quite large and we don't want to keep them around if we
242 // don't have to.
243 () => groups.clear(),
244 () => {
245 teardownAttempted = true;
246 // We only kill our subscription to the source if we have
247 // no active groups. As stated above, consider this scenario:
248 // source$.pipe(groupBy(fn), take(2)).
249 return activeGroups === 0;
250 }
251 );
252
253 // Subscribe to the source
254 source.subscribe(groupBySourceSubscriber);
255
256 /**
257 * Creates the actual grouped observable returned.
258 * @param key The key of the group
259 * @param groupSubject The subject that fuels the group
260 */
261 function createGroupedObservable(key: K, groupSubject: SubjectLike<any>) {
262 const result: any = new Observable<T>((groupSubscriber) => {
263 activeGroups++;
264 const innerSub = groupSubject.subscribe(groupSubscriber);
265 return () => {
266 innerSub.unsubscribe();
267 // We can kill the subscription to our source if we now have no more
268 // active groups subscribed, and a finalization was already attempted on
269 // the source.
270 --activeGroups === 0 && teardownAttempted && groupBySourceSubscriber.unsubscribe();
271 };
272 });
273 result.key = key;
274 return result;
275 }
276 });
277 }
278
279 /**
280 * An observable of values that is the emitted by the result of a {@link groupBy} operator,
281 * contains a `key` property for the grouping.
282 */
283 export interface GroupedObservable<K, T> extends Observable<T> {
284 /**
285 * The key value for the grouped notifications.
286 */
287 readonly key: K;
288 }