Reactive Programming in TypeScript: A Complete Guide to RxJS
Reactive programming is a development paradigm focused on asynchronous data streams and the propagation of changes. In the TypeScript ecosystem, the most powerful tool for implementing this paradigm is the RxJS library (Reactive Extensions for JavaScript). RxJS allows you to work with events, asynchronous requests, and application states as sequences of data that can be transformed, combined, and filtered using declarative operators.
Core Concepts of RxJS
At the heart of RxJS are three key entities:
- Observable — a data source that can generate values over time. An analogy to an array, but elements appear asynchronously.
- Observer — a data consumer that reacts to three types of events:
next(new value),error(error), andcomplete(stream completion). - Subscription — an object representing the execution of an Observable. It allows you to cancel the subscription and free resources.
import { Observable } from 'rxjs';
const observable = new Observable<number>(subscriber => { subscriber.next(1); subscriber.next(2); subscriber.next(3); setTimeout(() => { subscriber.next(4); subscriber.complete(); }, 1000);});
const subscription = observable.subscribe({ next: (value) => console.log(`Received: ${value}`), error: (err) => console.error(`Error: ${err}`), complete: () => console.log('Stream completed')});
// Cancel subscription after 500 mssetTimeout(() => subscription.unsubscribe(), 500);RxJS Operators: The Foundation of Reactive Transformations
Operators are pure functions that take one Observable and return a new Observable without modifying the original. They are divided into several categories:
- Creation:
of,from,interval,fromEvent - Transformation:
map,pluck,scan,buffer - Filtering:
filter,take,skip,distinctUntilChanged - Combination:
merge,concat,combineLatest,zip - Error Handling:
catchError,retry,retryWhen
import { fromEvent, interval } from 'rxjs';import { map, filter, debounceTime, distinctUntilChanged } from 'rxjs/operators';
// Example: reactive search with debounceconst searchInput = document.getElementById('search') as HTMLInputElement;const input$ = fromEvent(searchInput, 'input').pipe( map(event => (event.target as HTMLInputElement).value), filter(text => text.length >= 3), debounceTime(300), distinctUntilChanged());
input$.subscribe(searchTerm => { console.log(`Search: ${searchTerm}`); // Execute HTTP request});Subject: Hot and Cold Streams
Subject is a special type of Observable that is simultaneously both an observer and an observable. It allows multicasting (distributing) the same value to multiple subscribers. The main varieties:
Subject— basic, only passes new valuesBehaviorSubject— stores the last value and emits it to new subscribersReplaySubject— buffers the last N valuesAsyncSubject— only emits the last value after the stream completes
import { BehaviorSubject } from 'rxjs';
// Application state management Also in library
ErrorOr for C# (.NET): Complete Guide with Examples
Kotlin Security Crypto: Complete Guide with Code Examples
C# (.NET) Application Configuration: Microsoft.Extensions.Configuration
Sharp for JavaScript (Node.js): Complete Guide with Examples