RxJS
RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables. Observables are lazy collections of multiple values over time. They're used extensively in Angular for handling asynchronous operations like HTTP requests, user input events, and more. Operators allow you to transform, filter, and combine observable streams.
- RxJS (Reactive Extensions for JavaScript) is a library makes it easier to compose asynchronous or callback-based code.
- RxJS is still thought of as mostly an Angular tool by many, but TikTok’s React web app just saved 14.3KB by upgrading to RxJS 7
- a library for composing observable streams and optionally processing each item in the stream using an extensive set of operators.
RxJS enables reactive programming in Angular web apps by managing asynchronous data streams and events through observables, facilitating efficient handling of tasks like HTTP requests and user interactions. two reasons why learning Rx will benefit while writing Angular apps: Performance and Asynchronous Processing. one of Angular’s most powerful features is its deep integration with Rx and Functional Reactive Programming. forget Promise, setTimeout and setInterval and start doing things the Rx-way. event-based code means that it reacts to discrete events (like clicks, HTTP responses, or timer ticks) emitted over time as an observable stream, allowing you to subscribe and handle them declaratively as they occur. a declarative programming paradigm means you define what data or events you want to observe (e.g., user clicks, API responses) as observable streams, then reactively declare how to transform, filter, or combine them using operators—without imperatively managing state or callbacks—letting the system automatically push updates when changes occur.
HTTP
every HTTP request is an Observable, however HTTP requests automatically complete and do not require us to unsubscribe the observable.
HttpClientModule
The Angular HTTP Module has an RxJS Observable-based API. This means that calls to the HTTP module will return an observable, that we need to subscribe to one way or another.
//app.module.ts
import {HttpClientModule} from '@angular/common/http';
imports: [
HttpClientModule,
]
load() {
if(this.data) {
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get('https://jsonplaceholder.typicode.com').subscribe(data = {
this.data = data //error here
alert(JSON.stringify(data));
resolve(this.data);
});
});
}
Observable
Observable an interface to handle asynchronous operations
- Easily compose asynchronous or callback-based code
- whenever the data does arrive, do x
- define custom events to send observable data from child to parent component
- Handle AJAX requests and responses
ES7 observable services are patterns that allow you to effectively deal with data. Allowing you to parse, modify, and maintain data in an event-based system.
One advantage over Promises is that Observables can be cancelled.
Observer
the subscribe function Handle errors, data, and completion your code gets executed in these events
Observable
various data sources
- user input events, HTTP requests, code triggers
Subject
a subject is different from an Observable as its value can also be pushed in from the outside
- responsible for
- allow observers to register / unregister
Services With Observable: In combination, it is famous to work with REST API. In the following example there will be a Service in which an API will be accessed using GET request feature provided in the HttpClientModule in Angular, which in turn returns an observable. This observable will be subscribed by a component of the application and then shown on the page.
Observable | a stream of values emitted over time. In code, it is often represented with the dollar sign as a suffix.
- data rendered on the screen
- configuration/session/user preferences data
- state is the SPOT (single point of truth)
actions reducers asynchronous tasks
implementing state management with redux is a lot of work
"Redux is verbose" means that implementing state management with Redux requires writing a lot of repetitive, boilerplate code—such as defining actions, action creators, reducers, and switch-case logic—even for simple state changes, making it feel overly wordy and cumbersome compared to more concise alternatives like Angular’s NgRx with effects or React’s Context + useReducer.
These utility functions can be used for:
- Iterating through the values in a stream
- Mapping values to different types
- Filtering streams
- Composing multiple streams
Converting existing code for async operations into observables
You necessitate converting existing async code (e.g., Promises, callbacks) into RxJS observables when your Angular codebase requires complex asynchronous workflows that benefit from RxJS’s stream capabilities—such as:
- Chaining/combining multiple async sources (e.g.,
forkJoin,combineLatest,merge) - Canceling in-flight requests (via
unsubscribeortakeUntil) - Real-time reactivity (e.g., form value streams with
valueChanges, type-ahead search debouncing) - Error retry/backoff strategies (
retry,retryWhen) - Unified event + data stream handling (clicks + API + WebSocket in one pipeline)
If you're only doing simple await or one-off HTTP calls with no need for cancellation, transformation chains, or reactivity, stick with Promises—RxJS adds overhead. Convert only when the complexity justifies the stream abstraction.
ReactiveFormsModule
ReactiveFormsModule is an Angular module that enables reactive forms, a powerful, model-driven approach to handling form inputs by creating form controls in the component class (using FormGroup, FormControl, and FormArray) and binding them to the template declaratively—offering built-in validation, dynamic form updates, and seamless integration with RxJS observables for real-time reactivity and change tracking.
Observable operators
Observable operators are pure functions in RxJS that take an input observable and return a new observable, enabling you to transform, filter, combine, or control the stream of emitted values in a declarative, composable pipeline—common examples include:
- Transformation:
map,pluck,scan - Filtering:
filter,debounceTime,distinctUntilChanged,take,first - Combining:
merge,concat,combineLatest,withLatestFrom,zip - Error/Control:
catchError,retry,timeout,delay - Utility:
tap(side effects),switchMap(cancel inner observables)
Used via pipe():
http.get('/api').pipe(
map(data => data.users),
filter(users => users.length > 0),
switchMap(users => getDetails(users[0]))
).subscribe();
They are the core of reactive programming in Angular with RxJS—allowing clean, readable, and powerful async data flows.
Subjects
Subjects in RxJS are both Observable and Observer—they allow you to multicast values to multiple subscribers and manually push values with .next().
Subject vs BehaviorSubject
| Feature | Subject | BehaviorSubject |
|---|---|---|
| Initial value | None | Requires an initial value |
| Current value for late subscribers | ❌ Only future emissions | ✅ Replays the latest value |
| Use case | Event streams (e.g., clicks, messages) | State that always has a current value (e.g., user auth status, config) |
Example:
// Subject
const subject = new Subject<string>();
subject.subscribe(v => console.log('A:', v));
subject.next('Hello');
subject.subscribe(v => console.log('B:', v)); // late subscriber
subject.next('World');
// Output: A: Hello A: World B: World
// BehaviorSubject
const behavior = new BehaviorSubject<string>('Initial');
behavior.subscribe(v => console.log('X:', v)); // gets 'Initial' immediately
behavior.next('Updated');
behavior.subscribe(v => console.log('Y:', v)); // gets 'Updated' immediately
// Output: X: Initial X: Updated Y: Updated
Use Subject for event-like streams.
Use BehaviorSubject when you need current state accessible anytime (common in Angular services for shared state).