Lessons18. distinctUntilChanged: drop the repeats
Lessons · 18
18. distinctUntilChanged: drop the repeats
distinctUntilChanged — no neighboring duplicates
Sometimes a stream emits the same value twice in a row. A user presses and releases a key, say, but the text didn't change. Firing a fresh request for an identical value is wasteful. distinctUntilChanged() strips those repeats out.
['a', 'a', 'b', 'b', 'a'] → distinctUntilChanged()
// 'a' (new) → skip → 'b' (new) → skip → 'a' (new again)
// Result: a, b, a
An important detail
Only neighbors are compared. A value that appeared earlier, then changed and came back, counts as new. Example: a, a, b, a → a, b, a (the third a gets through because the previous output was b).
How values are compared
By default it uses strict equality (===). For objects that means comparison by reference. If you need to compare by a field, there's the form distinctUntilChanged((a, b) => ...).
Your task
- Inside
pipe, adddistinctUntilChanged(). - Expected output:
Query: ng → Query: rxjs → Query: ng. The neighboring repeats dropped out.
Solution spoiler · click to reveal
const { from, distinctUntilChanged } = Rx;
const query$ = from(['ng', 'ng', 'rxjs', 'rxjs', 'ng']).pipe(
distinctUntilChanged()
);
query$.subscribe(value => {
console.log('Query: ' + value);
}); script.ts
CONSOLE · Console output
Hit Run to see the result...