#rxjs
#tutorial
#intermediate
Day 4: Filtering Operators (take, first, debounceTime)
Day 4: Filtering & Timing
Sometimes you don’t need every value. You might want just the first one, or you want to wait until the user stops typing.
1. take & first
take(n): Emitsnvalues then completes.first(): Emits the first value then completes. Equivalent totake(1).
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
// Will emit 0, 1, 2, 3, 4 then Stop!
interval(1000).pipe(take(5)).subscribe(console.log);
2. distinctUntilChanged
Only emits if the current value is different from the last value. Great for checking state changes.
import { of } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
of(1, 1, 2, 2, 3, 1).pipe(
distinctUntilChanged()
).subscribe(console.log);
// Output: 1, 2, 3, 1
3. debounceTime
The champion of search inputs! It ignores values until n milliseconds have passed without another emission. “Wait for the user to stop typing.”
import { fromEvent } from 'rxjs';
import { debounceTime, map } from 'rxjs/operators';
const input = document.getElementById('search');
fromEvent(input, 'keyup').pipe(
map(event => event.target.value),
debounceTime(500) // Wait 500ms after last keystroke
).subscribe(searchTerm => {
console.log('Searching for:', searchTerm);
});
4. throttleTime
Different from debounce. throttleTime emits a value, then ignores all subsequent values for n milliseconds. Great for preventing button spam.
fromEvent(button, 'click').pipe(
throttleTime(1000)
).subscribe(() => console.log('I only fire once per second!'));
Homework for Day 4:
- Create a
subjector interval that emits rapidly. - Apply
debounceTime(100)and see what gets through. - Compare it with
throttleTime(100).
Tomorrow, we mix streams together with Combination Operators!