distinctOnChange

The distinctOnChange operator enhances RxJS Observables by not only preventing duplicate emissions (like distinctUntilChanged) but also executing a callback function when a value changes. This is useful for scenarios where you need to perform side effects, such as displaying a toast notification, when a value changes after the initial emission.

Examples

Example 1: Basic Usage

Execute a callback when distinct values are encountered:

import {distinctOnChange} from 'ngx-lift';
import {from} from 'rxjs';

from([1, 1, 2, 2, 3, 4, 4, 5])
  .pipe(distinctOnChange((prev, curr) => console.log(`Value changes from ${prev} to: ${curr}`)))
  .subscribe();

// Output:
// Value changes from 1 to: 2
// Value changes from 2 to: 3
// Value changes from 3 to: 4
// Value changes from 4 to: 5

Example 2: With Custom Comparator

Use a custom comparator function to determine equality:

import {distinctOnChange} from 'ngx-lift';
import {from} from 'rxjs';

interface User {
  id: number;
  name: string;
}

from([
  {id: 1, name: 'John'},
  {id: 1, name: 'John'},
  {id: 2, name: 'Jane'},
])
  .pipe(
    distinctOnChange(
      (prev, curr) => console.log(`User changed from ${prev.name} to ${curr.name}`),
      (prev, curr) => prev.id === curr.id
    )
  )
  .subscribe();

API Reference

distinctOnChange

RxJS operator that filters duplicate consecutive values and executes a callback when a distinct value is encountered.

Signature

distinctOnChange<T>(
  onChangeCallback: (previous: T, current: T) => void,
  comparator?: (previous: T, current: T) => boolean
): MonoTypeOperatorFunction<T>

Parameters

  • onChangeCallback: (previous: T, current: T) => void

    Callback function that triggers whenever a distinct value is encountered. Receives both the previous distinct value and the current value as arguments.

  • comparator?: (previous: T, current: T) => boolean

    (Optional) Function to determine whether two values are considered equal. Defaults to strict equality comparison (===).

Returns

An observable that emits distinct values and executes the callback on changes.