Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
In JavaScript runtimes that support Set, this operator uses a Set for improved performance. In other runtimes, it uses an Array with indexOf for checking distinctness.
Optional function to select which value you want to check as distinct. If provided, it projects each value from the source observable into a new value that will be checked for equality with previously projected values.If not provided, the operator uses each value from the source directly with an equality check against previous values.
Optional ObservableInput for flushing the internal HashSet of the operator. When the flushes Observable emits, the internal Set is cleared, allowing previously seen values to be emitted again.
Applies keySelector if provided, otherwise uses the value itself
Checks if the key exists in the Set
If not seen before: adds to Set and emits the value
If already seen: skips the value
If flushes Observable emits, the Set is cleared
Long-running distinct operations can result in memory leaks as the Set grows. Use the flushes parameter to periodically clear the Set, or use distinctUntilChanged if you only need to compare consecutive values.
import { distinct } from 'rxjs';interface Vote { userId: string; pollId: string; choice: string;}const votes$ = getVotes();// Ensure each user can only vote once per pollconst uniqueVotes$ = votes$.pipe( distinct(vote => `${vote.userId}:${vote.pollId}`));uniqueVotes$.subscribe(vote => { recordVote(vote);});
For objects, the keySelector function is essential. Without it, distinct uses reference equality, which means two objects with identical properties will be considered different.
import { interval, distinct, take } from 'rxjs';// Memory usage grows with each unique valueconst numbers$ = interval(100).pipe( take(10000), distinct() // Will store 10,000 values in memory);// Better: Use flushes to limit memory growthconst betterNumbers$ = interval(100).pipe( take(10000), distinct( x => x, interval(10000) // Flush every 10 seconds ));