Operators are pure functions that transform streams - like different ninja techniques changing the way information is passed.
1import { map, switchMap, mergeMap, concatMap, exhaustMap } from 'rxjs/operators';
2
3// map - transforms each element
4source$.pipe(
5 map(value => value * 2)
6);
7
8// switchMap - switches to a new stream, cancels the previous one
9// Ideal for search (cancel previous query)
10searchInput$.pipe(
11 switchMap(query => this.http.get(\`/search?q=\${query}\`))
12);
13
14// mergeMap - parallel execution of all
15// Good when order doesn't matter
16ids$.pipe(
17 mergeMap(id => this.http.get(\`/item/\${id}\`))
18);
19
20// concatMap - sequential, preserves order
21// When order is important
22actions$.pipe(
23 concatMap(action => this.saveAction(action))
24);
25
26// exhaustMap - ignores new ones until the current one completes
27// Ideal for save buttons (preventing double clicks)
28saveButton$.pipe(
29 exhaustMap(() => this.saveData())
30);1import { filter, take, takeUntil, takeWhile, distinctUntilChanged, debounceTime } from 'rxjs/operators';
2
3// filter - passes only matching elements
4numbers$.pipe(
5 filter(n => n > 5)
6);
7
8// take - takes the first n elements
9numbers$.pipe(
10 take(3) // Only the first 3
11);
12
13// distinctUntilChanged - removes consecutive duplicates
14values$.pipe(
15 distinctUntilChanged() // [1,1,2,2,3,1] -> [1,2,3,1]
16);
17
18// debounceTime - waits for a pause in emissions
19searchInput$.pipe(
20 debounceTime(300) // Waits 300ms without new values
21);1import { combineLatest, forkJoin, merge, concat, zip } from 'rxjs';
2
3// combineLatest - emits when any emits (after first emissions)
4combineLatest([user$, settings$]).subscribe(([user, settings]) => {
5 console.log(user, settings);
6});
7
8// forkJoin - waits for all to complete (like Promise.all)
9forkJoin([
10 this.http.get('/api/samurai'),
11 this.http.get('/api/weapons')
12]).subscribe(([samurai, weapons]) => {
13 // Both completed
14});
15
16// merge - combines streams in parallel
17merge(clicks$, keyups$).subscribe(event => {
18 console.log('Event:', event);
19});