distinctOnChange

RxJS provides the distinctUntilChanged operator, which is useful for preventing duplicated emissions within an observable stream. However, there are scenarios where we not only want to avoid duplicates but also need to execute a callback function, such as displaying a toast, when a value changes after the initial emission.

Enter the distinctOnChange operator—an lift designed to enhance RxJS Observables. This operator takes two crucial parameters: onChangeCallback and comparator. The onChangeCallback is a callback function that triggers whenever a distinct value is encountered in the observable stream. It receives both the previous distinct value and the current value as arguments, allowing you to perform specific actions based on this change. Meanwhile, the optional comparator function, with a default behavior of strict equality comparison (===), determines whether two values are considered equal.

The distinctOnChange operator is particularly valuable in scenarios where you not only seek distinct values but also desire to execute custom logic or side effects when changes occur in the observable data. This flexibility makes it a powerful tool for handling various real-time or user interaction scenarios within your RxJS-powered applications. Integrate distinctOnChange into your projects to streamline asynchronous data processing, make observables more versatile, and enhance the overall reactivity of your application.

Example Code

import {distinctOnChange} from 'ngx-lift';
// ... other imports

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