Debian Codegraph @

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

raw
1 import { MonoTypeOperatorFunction } from '../types';
2 import { identity } from '../util/identity';
3 import { operate } from '../util/lift';
4 import { createOperatorSubscriber } from './OperatorSubscriber';
5
6 export function distinctUntilChanged<T>(comparator?: (previous: T, current: T) => boolean): MonoTypeOperatorFunction<T>;
7 export function distinctUntilChanged<T, K>(
8 comparator: (previous: K, current: K) => boolean,
9 keySelector: (value: T) => K
10 ): MonoTypeOperatorFunction<T>;
11
12 /**
13 * Returns a result {@link Observable} that emits all values pushed by the source observable if they
14 * are distinct in comparison to the last value the result observable emitted.
15 *
16 * When provided without parameters or with the first parameter (`{@link distinctUntilChanged#comparator comparator}`),
17 * it behaves like this:
18 *
19 * 1. It will always emit the first value from the source.
20 * 2. For all subsequent values pushed by the source, they will be compared to the previously emitted values
21 * using the provided `comparator` or an `===` equality check.
22 * 3. If the value pushed by the source is determined to be unequal by this check, that value is emitted and
23 * becomes the new "previously emitted value" internally.
24 *
25 * When the second parameter (`{@link distinctUntilChanged#keySelector keySelector}`) is provided, the behavior
26 * changes:
27 *
28 * 1. It will always emit the first value from the source.
29 * 2. The `keySelector` will be run against all values, including the first value.
30 * 3. For all values after the first, the selected key will be compared against the key selected from
31 * the previously emitted value using the `comparator`.
32 * 4. If the keys are determined to be unequal by this check, the value (not the key), is emitted
33 * and the selected key from that value is saved for future comparisons against other keys.
34 *
35 * ## Examples
36 *
37 * A very basic example with no `{@link distinctUntilChanged#comparator comparator}`. Note that `1` is emitted more than once,
38 * because it's distinct in comparison to the _previously emitted_ value,
39 * not in comparison to _all other emitted values_.
40 *
41 * ```ts
42 * import { of, distinctUntilChanged } from 'rxjs';
43 *
44 * of(1, 1, 1, 2, 2, 2, 1, 1, 3, 3)
45 * .pipe(distinctUntilChanged())
46 * .subscribe(console.log);
47 * // Logs: 1, 2, 1, 3
48 * ```
49 *
50 * With a `{@link distinctUntilChanged#comparator comparator}`, you can do custom comparisons. Let's say
51 * you only want to emit a value when all of its components have
52 * changed:
53 *
54 * ```ts
55 * import { of, distinctUntilChanged } from 'rxjs';
56 *
57 * const totallyDifferentBuilds$ = of(
58 * { engineVersion: '1.1.0', transmissionVersion: '1.2.0' },
59 * { engineVersion: '1.1.0', transmissionVersion: '1.4.0' },
60 * { engineVersion: '1.3.0', transmissionVersion: '1.4.0' },
61 * { engineVersion: '1.3.0', transmissionVersion: '1.5.0' },
62 * { engineVersion: '2.0.0', transmissionVersion: '1.5.0' }
63 * ).pipe(
64 * distinctUntilChanged((prev, curr) => {
65 * return (
66 * prev.engineVersion === curr.engineVersion ||
67 * prev.transmissionVersion === curr.transmissionVersion
68 * );
69 * })
70 * );
71 *
72 * totallyDifferentBuilds$.subscribe(console.log);
73 *
74 * // Logs:
75 * // { engineVersion: '1.1.0', transmissionVersion: '1.2.0' }
76 * // { engineVersion: '1.3.0', transmissionVersion: '1.4.0' }
77 * // { engineVersion: '2.0.0', transmissionVersion: '1.5.0' }
78 * ```
79 *
80 * You can also provide a custom `{@link distinctUntilChanged#comparator comparator}` to check that emitted
81 * changes are only in one direction. Let's say you only want to get
82 * the next record temperature:
83 *
84 * ```ts
85 * import { of, distinctUntilChanged } from 'rxjs';
86 *
87 * const temps$ = of(30, 31, 20, 34, 33, 29, 35, 20);
88 *
89 * const recordHighs$ = temps$.pipe(
90 * distinctUntilChanged((prevHigh, temp) => {
91 * // If the current temp is less than
92 * // or the same as the previous record,
93 * // the record hasn't changed.
94 * return temp <= prevHigh;
95 * })
96 * );
97 *
98 * recordHighs$.subscribe(console.log);
99 * // Logs: 30, 31, 34, 35
100 * ```
101 *
102 * Selecting update events only when the `updatedBy` field shows
103 * the account changed hands.
104 *
105 * ```ts
106 * import { of, distinctUntilChanged } from 'rxjs';
107 *
108 * // A stream of updates to a given account
109 * const accountUpdates$ = of(
110 * { updatedBy: 'blesh', data: [] },
111 * { updatedBy: 'blesh', data: [] },
112 * { updatedBy: 'ncjamieson', data: [] },
113 * { updatedBy: 'ncjamieson', data: [] },
114 * { updatedBy: 'blesh', data: [] }
115 * );
116 *
117 * // We only want the events where it changed hands
118 * const changedHands$ = accountUpdates$.pipe(
119 * distinctUntilChanged(undefined, update => update.updatedBy)
120 * );
121 *
122 * changedHands$.subscribe(console.log);
123 * // Logs:
124 * // { updatedBy: 'blesh', data: Array[0] }
125 * // { updatedBy: 'ncjamieson', data: Array[0] }
126 * // { updatedBy: 'blesh', data: Array[0] }
127 * ```
128 *
129 * @see {@link distinct}
130 * @see {@link distinctUntilKeyChanged}
131 *
132 * @param comparator A function used to compare the previous and current keys for
133 * equality. Defaults to a `===` check.
134 * @param keySelector Used to select a key value to be passed to the `comparator`.
135 *
136 * @return A function that returns an Observable that emits items from the
137 * source Observable with distinct values.
138 */
139 export function distinctUntilChanged<T, K>(
140 comparator?: (previous: K, current: K) => boolean,
141 keySelector: (value: T) => K = identity as (value: T) => K
142 ): MonoTypeOperatorFunction<T> {
143 // We've been allowing `null` do be passed as the `compare`, so we can't do
144 // a default value for the parameter, because that will only work
145 // for `undefined`.
146 comparator = comparator ?? defaultCompare;
147
148 return operate((source, subscriber) => {
149 // The previous key, used to compare against keys selected
150 // from new arrivals to determine "distinctiveness".
151 let previousKey: K;
152 // Whether or not this is the first value we've gotten.
153 let first = true;
154
155 source.subscribe(
156 createOperatorSubscriber(subscriber, (value) => {
157 // We always call the key selector.
158 const currentKey = keySelector(value);
159
160 // If it's the first value, we always emit it.
161 // Otherwise, we compare this key to the previous key, and
162 // if the comparer returns false, we emit.
163 if (first || !comparator!(previousKey, currentKey)) {
164 // Update our state *before* we emit the value
165 // as emission can be the source of re-entrant code
166 // in functional libraries like this. We only really
167 // need to do this if it's the first value, or if the
168 // key we're tracking in previous needs to change.
169 first = false;
170 previousKey = currentKey;
171
172 // Emit the value!
173 subscriber.next(value);
174 }
175 })
176 );
177 });
178 }
179
180 function defaultCompare(a: any, b: any) {
181 return a === b;
182 }