Introduction
The distinctUntilChanged()
operator in Angular, part of the RxJS library, is used to filter out consecutive duplicate values emitted by an observable. This operator ensures that only distinct values are passed through, preventing consecutive emissions of the same value from reaching the subscriber.
Installation
Before using distinctUntilChanged()
, ensure you have RxJS installed in your Angular project. If it's not already installed, you can add it using npm:
npm install rxjs
Usage
Import the distinctUntilChanged
operator from RxJS in the component or service where you want to use it:
import { distinctUntilChanged } from 'rxjs/operators';
Example
Let's illustrate how distinctUntilChanged()
works with a practical example.
Service Definition
Assume you have a service that provides an observable stream of numeric data:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data = [1, 1, 2, 3, 3, 3, 4, 5];
getData(): Observable<number> {
return of(...this.data);
}
}
Component Implementation
In your component, you can consume this service and use the distinctUntilChanged()
operator to filter out consecutive duplicate values.
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
import { distinctUntilChanged } from 'rxjs/operators';
@Component({
selector: 'app-data-list',
template: `
<h2>Distinct Data</h2>
<ul>
<li *ngFor="let value of distinctValues$ | async">{{ value }}</li>
</ul>
`
})
export class DataListComponent implements OnInit {
distinctValues$: Observable<number>;
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.distinctValues$ = this.dataService.getData().pipe(
distinctUntilChanged()
);
}
}
In this example
this.dataService.getData()
returns an observable that emits a sequence of numbers.
distinctUntilChanged()
is used within the pipe()
method to ensure that only distinct values are emitted. Consecutive duplicates are filtered out.
Template Usage
In the component's template (data-list.component.html
), subscribe to distinctValues$
using the async
pipe to display the distinct values:
<h2>Distinct Data</h2>
<ul>
<li *ngFor="let value of distinctValues$ | async">{{ value }}</li>
</ul>
Summary
The distinctUntilChanged()
operator is useful when you need to filter out consecutive duplicate values emitted by an observable. It's commonly used to optimize data processing and ensure that only unique changes are propagated through the reactive pipeline in Angular applications.