Design Patterns
RxJS
RxJS brings Reactive Extensions to JavaScript, modelling async data as observable streams. Master Observables, Subjects, higher-order operators (switchMap, mergeMap), error handling, and reactive patterns used in Angular, React, and Node.js.
What is RxJS?
RxJS is a library for reactive programming with Observables, streams of values over time such as clicks, keystrokes, WebSocket messages or HTTP responses. You transform streams with operators like map, filter, debounceTime and switchMap, then subscribe to receive results. It's built into Angular and is useful for complex event coordination.
import { fromEvent, debounceTime, map, switchMap } from "rxjs";
fromEvent(input, "input").pipe(
map((e) => e.target.value),
debounceTime(300),
switchMap((q) => fetch(`/api/search?q=${q}`).then((r) => r.json()))
).subscribe(render);Most Used Operators
Transformation
map(fn)scan(acc, fn)pluck('key')mapTo(value)
Filtering
filter(pred)take(n)skip(n)distinctUntilChanged()debounceTime(ms)throttleTime(ms)
Combination
combineLatest([...])merge(...)forkJoin([...])zip(...)
Higher-order
switchMap(fn)mergeMap(fn)concatMap(fn)exhaustMap(fn)
Error Handling
catchError(fn)retry(n)retryWhen(fn)onErrorResumeNext(...)
Utility
tap(fn)delay(ms)finalize(fn)timeout(ms)shareReplay(N)
Common Pitfalls
Not unsubscribing from Observables — memory leaks and ghost event handlers piling up
Always unsubscribe. In Angular: ngOnDestroy + takeUntil(destroy$). In React: return sub.unsubscribe from useEffect.
Using mergeMap for search — old slow requests arrive after newer ones, showing stale results
Use switchMap for search/autocomplete. switchMap cancels the previous request when a new value arrives.
Creating Observables inside subscribe — nested subscribes are the RxJS anti-pattern
Flatten with higher-order operators: switchMap/mergeMap/concatMap instead of subscribe() inside subscribe().
Using Subject as a service and forgetting to complete it — subscribers keep listening forever
Complete Subjects when the service is destroyed. Use takeUntil or async pipes in Angular to auto-unsubscribe.
Interactive Demo
Code Editor
<input id="q" placeholder="Search (debounced stream)">
<p id="out"></p>Preview
RxJS: summary
Key points
switchMapcancels the previous inner request, which prevents out-of-order search results.- Always unsubscribe (or use
takeUntil) to avoid leaks. - For simple async work, promises and
async/awaitare easier.
Frequently asked questions
›Observable vs Promise?
A Promise delivers one value once and starts immediately. An Observable can deliver many values over time, is lazy until subscribed, and can be cancelled.