2. RxJS Operators Deep Dive
map, switchMap, mergeMap, concatMap — the operators that do the real work
Operators are what make RxJS worth learning. An Observable on its own is just a stream of values. Operators let you transform, filter, combine, and control those values as they flow through the pipeline. Every operator takes an Observable as input and returns a new Observable as output — the original is never modified.
There are over 100 operators in RxJS, but you'll use about 15 of them in 95% of your work. This article covers the ones that matter most, organized by what they do.
Transformation Operators
map — transform each value
The workhorse. Takes each emitted value and applies a function to it. If you know Array.prototype.map, this is the same idea, but for streams.
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
of(1, 2, 3).pipe(
map(n => n * 10)
).subscribe(console.log);
// 10
// 20
// 30
In Angular, you'll use map constantly to reshape API responses:
this.http.get<ApiResponse>('/api/users').pipe(
map(response => response.data), // unwrap envelope
map(users => users.filter(u => u.active)) // keep only active
).subscribe(activeUsers => {
this.users = activeUsers;
});
pluck / nested map — extract a property
import { fromEvent } from 'rxjs';
import { map } from 'rxjs/operators';
// Extract the value from input events
fromEvent<InputEvent>(inputEl, 'input').pipe(
map(event => (event.target as HTMLInputElement).value)
).subscribe(text => console.log(text));
scan — running accumulator (like reduce, but emits each step)
import { of } from 'rxjs';
import { scan } from 'rxjs/operators';
of(1, 2, 3, 4, 5).pipe(
scan((acc, value) => acc + value, 0)
).subscribe(console.log);
// 1 (0 + 1)
// 3 (1 + 2)
// 6 (3 + 3)
// 10 (6 + 4)
// 15 (10 + 5)
scan is invaluable for maintaining running state in a stream — counters, accumulated lists, rolling averages.
Filtering Operators
filter — let values through conditionally
import { from } from 'rxjs';
import { filter } from 'rxjs/operators';
from([1, 2, 3, 4, 5, 6]).pipe(
filter(n => n % 2 === 0)
).subscribe(console.log);
// 2
// 4
// 6
distinctUntilChanged — skip consecutive duplicates
import { of } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
of(1, 1, 2, 2, 2, 3, 1, 1).pipe(
distinctUntilChanged()
).subscribe(console.log);
// 1
// 2
// 3
// 1 <-- not a consecutive duplicate
Essential for form controls — valueChanges can emit the same value repeatedly (e.g., pasting the same text), and you don't want to trigger a search for every identical emission.
take and first — limit emissions
import { interval } from 'rxjs';
import { take, first } from 'rxjs/operators';
// Take exactly 3 values, then complete
interval(1000).pipe(
take(3)
).subscribe(console.log);
// 0 (at 1s)
// 1 (at 2s)
// 2 (at 3s)
// (completes)
// Take only the first value that matches a condition
interval(1000).pipe(
first(n => n > 2)
).subscribe(console.log);
// 3 (at 4s, then completes)
takeUntil — unsubscribe when another Observable emits
This is the classic Angular pattern for cleaning up subscriptions:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({ selector: 'app-timer', template: '{{ count }}' })
export class TimerComponent implements OnInit, OnDestroy {
count = 0;
private destroy$ = new Subject<void>();
ngOnInit() {
interval(1000).pipe(
takeUntil(this.destroy$)
).subscribe(n => this.count = n);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
When the component is destroyed, destroy$ emits, and takeUntil automatically unsubscribes from the interval. No manual Subscription tracking needed.
debounceTime and throttleTime — rate limiting
import { fromEvent } from 'rxjs';
import { debounceTime, throttleTime } from 'rxjs/operators';
const input = document.querySelector('input');
// debounceTime: wait until the user STOPS typing for 300ms
fromEvent(input, 'input').pipe(
debounceTime(300)
).subscribe(() => console.log('user paused typing'));
// throttleTime: emit at most once every 300ms (drops intermediate values)
fromEvent(document, 'scroll').pipe(
throttleTime(300)
).subscribe(() => console.log('scroll event'));
Debounce vs. Throttle
Debounce waits for silence — it only emits after a gap with no new values.
Use it for search inputs.
Throttle emits on a regular cadence — at most one value per interval.
Use it for scroll and resize events.
Higher-Order Mapping: The Big Four
These are the operators that cause the most confusion — and the ones you need to understand most deeply. They all solve the same problem: what do you do when an Observable emits another Observable?
The scenario: you have a stream of search terms, and for each term you want to make an HTTP request (which returns an Observable). That's an Observable of Observables — a "higher-order" Observable. The question is: how do you flatten it?
switchMap — cancel previous, switch to latest
When a new value arrives, switchMap unsubscribes from the previous inner Observable and subscribes to the new one. Only one inner Observable is active at a time.
import { fromEvent } from 'rxjs';
import { switchMap, debounceTime, map } from 'rxjs/operators';
const search$ = fromEvent<InputEvent>(input, 'input').pipe(
map(e => (e.target as HTMLInputElement).value),
debounceTime(300),
switchMap(term =>
this.http.get<Result[]>(`/api/search?q=${term}`)
)
);
Use when: You only care about the latest request. If the user types "ang", then "angular", the request for "ang" is cancelled. This is the right choice for search-as-you-type, route parameter changes, and dropdown selections.
switchMap timeline
Source: --a-------b-------c--|
\ \ \
Inner: a1-a2 b1-b2 c1-c2
X X
Output: ---a1----b1------c1-c2|
a's inner is cancelled when b arrives.
b's inner is cancelled when c arrives.
c's inner runs to completion.
mergeMap (aka flatMap) — run all in parallel
When a new value arrives, mergeMap subscribes to the new inner Observable without cancelling any previous ones. All inner Observables run concurrently.
import { from } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
const userIds = [1, 2, 3, 4, 5];
from(userIds).pipe(
mergeMap(id =>
this.http.get<User>(`/api/users/${id}`)
)
).subscribe(user => console.log(user));
// Results arrive in whatever order the requests complete
Use when: You want maximum throughput and don't care about order. Bulk operations — saving multiple records, uploading multiple files, firing off independent requests.
You can limit concurrency with a second argument:
from(urls).pipe(
mergeMap(url => this.http.get(url), 3) // at most 3 concurrent requests
).subscribe(response => { /* ... */ });
Order is not guaranteed
With mergeMap, results arrive in completion order, not emission order.
If request 3 finishes before request 1, you'll get result 3 first.
If order matters, use concatMap.
concatMap — run one at a time, in order
When a new value arrives, concatMap queues the new inner Observable and waits until the current one completes before subscribing to the next.
import { from } from 'rxjs';
import { concatMap, delay } from 'rxjs/operators';
from(['first', 'second', 'third']).pipe(
concatMap(msg =>
of(msg).pipe(delay(1000)) // simulate async work
)
).subscribe(console.log);
// "first" (at 1s)
// "second" (at 2s)
// "third" (at 3s)
Use when: Order matters and you can't have overlap. Sequential writes to a database, step-by-step animations, ordered API calls where each depends on the previous one completing.
exhaustMap — ignore new values while busy
When a new value arrives while an inner Observable is still active, exhaustMap drops the new value entirely. It only subscribes to a new inner Observable when the current one has completed.
import { fromEvent } from 'rxjs';
import { exhaustMap } from 'rxjs/operators';
fromEvent(submitButton, 'click').pipe(
exhaustMap(() =>
this.http.post('/api/orders', this.orderData)
)
).subscribe(response => {
console.log('order placed');
});
Use when: You want to prevent duplicate submissions. The user clicks "Submit" three times — only the first click triggers a request. The other two are ignored because the first request is still in flight.
Choosing the Right One
| Operator | Previous inner | New values while busy | Best for |
|---|---|---|---|
switchMap |
Cancelled | Replaces current | Search, route params, latest-wins |
mergeMap |
Kept running | Runs in parallel | Bulk ops, independent requests |
concatMap |
Kept running | Queued | Ordered sequences, writes |
exhaustMap |
Kept running | Dropped | Form submissions, login |
The golden rule
If you're unsure, start with switchMap. It's the safest default because it
automatically cleans up stale work. Only reach for the others when you specifically need
their behavior.
Try It Yourself — Operator Pipeline
Pick a source, then click operators to add them to the pipeline. Watch how each stage transforms or filters values. Solid circles are values that pass through; dashed outlines are values filtered out at that stage; dots mark values eliminated earlier.
Utility Operators
tap — side effects without modifying the stream
tap lets you "peek" at values without affecting them. Use it for logging, debugging, or triggering side effects.
this.http.get<User[]>('/api/users').pipe(
tap(users => console.log('raw response:', users)),
map(users => users.filter(u => u.active)),
tap(active => console.log('after filter:', active.length, 'users'))
).subscribe(users => {
this.users = users;
});
catchError — handle errors in the stream
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';
this.http.get<User[]>('/api/users').pipe(
catchError(error => {
console.error('request failed:', error);
return of([]); // return a fallback Observable
})
).subscribe(users => {
this.users = users; // [] if the request failed
});
catchError receives the error and must return a new Observable. The subscriber never sees the error — it just gets the fallback values. This keeps your stream alive.
retry and retryWhen — automatic retries
import { retry, delay } from 'rxjs/operators';
this.http.get('/api/flaky-endpoint').pipe(
retry({ count: 3, delay: 1000 }) // retry up to 3 times, 1s between attempts
).subscribe({
next: data => console.log('success:', data),
error: err => console.log('failed after 3 retries:', err)
});
startWith — prepend a value
import { startWith } from 'rxjs/operators';
this.searchControl.valueChanges.pipe(
startWith(''), // emit '' immediately so the initial state is defined
debounceTime(300),
switchMap(term => this.search(term))
).subscribe(results => {
this.results = results;
});
shareReplay — multicast and replay the last value
By default, each subscriber to a cold Observable gets its own execution. shareReplay makes the Observable hot — all subscribers share a single execution, and late subscribers get the last N emitted values.
import { shareReplay } from 'rxjs/operators';
// Without shareReplay: each subscriber triggers a new HTTP request
// With shareReplay: one request, result shared with all subscribers
const users$ = this.http.get<User[]>('/api/users').pipe(
shareReplay(1)
);
// Both components get the same data from a single request
users$.subscribe(users => this.headerUserCount = users.length);
users$.subscribe(users => this.userList = users);
This is essential for sharing expensive work (HTTP requests, complex computations) across multiple subscribers.
Combining Everything: A Real Angular Service
Here's how these operators come together in a real-world Angular service:
@Injectable({ providedIn: 'root' })
export class ProductService {
private refreshTrigger$ = new Subject<void>();
constructor(private http: HttpClient) {}
getProducts(categoryId$: Observable<string>): Observable<Product[]> {
return combineLatest([
categoryId$,
this.refreshTrigger$.pipe(startWith(undefined))
]).pipe(
debounceTime(100),
switchMap(([categoryId]) =>
this.http.get<Product[]>(`/api/products?category=${categoryId}`).pipe(
retry({ count: 2, delay: 1000 }),
catchError(err => {
console.error('Failed to load products:', err);
return of([]);
})
)
),
shareReplay(1)
);
}
refresh() {
this.refreshTrigger$.next();
}
}
This single pipeline handles: reloading when the category changes, manual refresh triggers, debouncing rapid changes, automatic retries, error fallbacks, and sharing the result across multiple subscribers.
What's Next
You've mastered individual stream transformations. The next article covers combining streams — merge, combineLatest, forkJoin, zip, and withLatestFrom — the operators for coordinating multiple Observables.