What is RxJS and how is it used in Angular?
Answer
RxJS (Reactive Extensions for JavaScript) is a library for composing asynchronous and event-based programs using observable sequences. Angular uses RxJS extensively for HTTP requests, user input handling, routing, and forms. Core concepts: (1) Observable: a stream of values over time — lazy, doesn't execute until subscribed. Cold observable: each subscriber gets its own execution (HTTP requests). Hot observable: shares one execution (UI events, WebSocket); (2) Observer: subscribes to an observable with next (value), error (error), and complete (done) callbacks; (3) Subject: both an Observable and an Observer — multicast (many subscribers). Types: Subject, BehaviorSubject (stores latest value, new subscribers get it immediately), ReplaySubject (stores N values), AsyncSubject (emits only the last value on completion); (4) Operators: pure functions that transform, filter, combine observables. Imported from "rxjs/operators". Key operators: Transformation: map, switchMap, mergeMap, concatMap, exhaustMap; Filtering: filter, take, takeUntil, debounceTime, distinctUntilChanged, skip; Combination: combineLatest, merge, zip, forkJoin, withLatestFrom; Error handling: catchError, retry, retryWhen; Utility: tap, delay, shareReplay, startWith, scan. Avoiding memory leaks: always unsubscribe: use takeUntil with a destroy$ Subject, take(1) for single-value streams, or async pipe (auto-unsubscribes). Angular-specific: EventEmitter extends Subject; ActivatedRoute params is an Observable; form value changes is an Observable; HttpClient returns Observables.
Previous
What is Angular Universal (SSR)?
Next
What is the difference between switchMap, mergeMap, concatMap, and exhaustMap?
More Angular Questions
View all →- Intermediate What is the difference between switchMap, mergeMap, concatMap, and exhaustMap?
- Intermediate What is the difference between Subject, BehaviorSubject, ReplaySubject, and AsyncSubject?
- Intermediate What is the Angular NgRx state management library?
- Intermediate What is Angular lazy loading and preloading strategy?
- Intermediate What is Angular change detection with OnPush strategy?