Skip to content

Function: distinctUntilKeyChanged()

distinctUntilKeyChanged<T>(key, comparator?): Operator<T, T>

Defined in: operators/distinctUntilKeyChanged.ts:18

Creates a stream operator that filters out consecutive values from the source stream if a specified key's value has not changed.

This operator is a specialized version of distinctUntilChanged. It is designed to work with streams of objects and checks for uniqueness based on the value of a single property (key).

Type Parameters

T

T extends object = any

The type of the objects in the stream. Must extend object.

Parameters

key

keyof T

The name of the property to check for changes.

comparator?

(prev, curr) => CallbackReturnType<boolean>

An optional function to compare the previous and current values of the key. It should return true if the values are considered the same. If not provided, strict inequality (!==) is used.

Returns

Operator<T, T>

An Operator instance that can be used in a stream's pipe method.

Examples

From distinctUntilKeyChanged.spec.ts:12

typescript
let subject: ReturnType<typeof createSubject<any>> = createSubject<any>();

let source: Stream<any> = subject;

const distinctStream = source.pipe(distinctUntilKeyChanged('key'));
const results: any[] = [];
const consumptionPromise = (async () => {
  for await (const value of eachValueFrom(distinctStream)) {
    results.push(value);
  }
})();
subject.next({ key: 1, value: 'a' });
subject.next({ key: 1, value: 'b' });
subject.next({ key: 2, value: 'c' });
subject.next({ key: 2, value: 'd' });
subject.next({ key: 3, value: 'e' });
subject.complete();
await consumptionPromise;
expect(results).toEqual([
  { key: 1, value: 'a' },
  { key: 2, value: 'c' },
  { key: 3, value: 'e' },
]);

Released under the MIT License.