Performance: filter operator for selection
This affects how quickly the UI updates when filtering data streams, impacting interaction responsiveness and rendering speed.
import { Component } from '@angular/core'; import { Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators'; @Component({ selector: 'app-filter', template: `<input (input)="onInput($event)" aria-label="Filter items" /> <ul><li *ngFor="let item of filteredItems">{{item}}</li></ul>` }) export class FilterComponent { items = ['apple', 'banana', 'cherry', 'date']; filteredItems = this.items; input$ = new Subject<string>(); constructor() { this.input$.pipe( map(value => value.trim()), debounceTime(300), distinctUntilChanged(), filter(value => value.length > 0) ).subscribe(value => { this.filteredItems = this.items.filter(item => item.includes(value)); }); } onInput(event: Event) { const input = (event.target as HTMLInputElement).value; this.input$.next(input); } }
import { Component } from '@angular/core'; import { Subject } from 'rxjs'; @Component({ selector: 'app-filter', template: `<input (input)="onInput($event)" /> <ul><li *ngFor="let item of filteredItems">{{item}}</li></ul>` }) export class FilterComponent { items = ['apple', 'banana', 'cherry', 'date']; filteredItems = this.items; input$ = new Subject<string>(); constructor() { this.input$.subscribe(value => { this.filteredItems = this.items.filter(item => item.includes(value)); }); } onInput(event: Event) { const input = (event.target as HTMLInputElement).value; this.input$.next(input); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Immediate filter on every keystroke | Multiple updates per input | Multiple reflows per keystroke | High paint cost due to frequent changes | [X] Bad |
| Filter with debounce and distinctUntilChanged | Single update after typing pause | Single reflow per filter | Lower paint cost with fewer updates | [OK] Good |
filter operator do in Angular's RxJS streams?filter operator inside an RxJS pipe() in Angular?import { of } from 'rxjs';
import { filter } from 'rxjs/operators';
of(1, 5, 10, 15).pipe(
filter(x => x > 5)
).subscribe(console.log);source$.pipe(
filter(x => {
if (x % 2 === 0) return true;
})
).subscribe(console.log);pipe()?users$.pipe( filter( /* your code here */ ) ).subscribe(activeAdults => console.log(activeAdults));
Pass the test and this pattern moves unknown