RxJS and change detection in Angular
An observable is a stream of values over time. It does nothing until someone subscribes, and you can cancel it. Use switchMap for search and exhaustMap for the place-order button, and always close a subscription with the async pipe, takeUntilDestroyed or toSignal. With OnPush and signals, Angular only checks the components that really changed.
Author: bezzad
Contents
The problem: a search box that shows the wrong results
Our online shop has a search box. A user on a phone with a slow connection types “shoes”. The old code was:
this.query.valueChanges.subscribe(q => {
this.http.get<Product[]>('/api/products', { params: { q } })
.subscribe(products => (this.results = products));
});
- For each letter, one request goes to the server. Five letters mean five requests.
- Responses do not arrive in order. If the response for “sho” arrives after the response for “shoes”, the page shows the results for “sho”.
- No subscription is ever closed. The user leaves the page, but the code still listens.
A few RxJS operators and a few simple rules fix these problems. After that, we look at how Angular knows when to update the page.
Observable vs Promise
A promise is one answer in the future. An observable is a stream of values over time.
| Feature | Promise | Observable |
|---|---|---|
| When does it start? | Right away, when it is created | Only when someone subscribes (lazy) |
| How many values? | Exactly one | Zero, one or many |
| Cancel | No built-in way | With unsubscribe |
| Shop example | An async function | Typing in the search box, the sale timer |
HttpClient returns a cold observable
The get method of HttpClient does not send the request right away. It returns a “cold” observable. That means each subscribe makes a new request:
const products$ = this.http.get<Product[]>('/api/products');
// Nothing is sent yet.
products$.subscribe(p => console.log('first', p.length)); // request 1
products$.subscribe(p => console.log('second', p.length)); // request 2
- If nobody subscribes, no request goes out. This is sometimes the “why was the save request never sent?” bug.
- If two places in a template connect to the same observable with two async pipes, two requests go out.
- The simple fix: subscribe once (for example with toSignal) and read the result in many places. Or share one response between many subscribers with the shareReplay operator.
Subscribing and unsubscribing
A subscription that is never closed lives as long as the browser tab. The component is gone, but the timer still runs. If the user comes back to the same page ten times, we have ten timers.
We have three safe ways:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
import { Analytics } from './analytics';
@Component({
selector: 'app-flash-sale',
imports: [AsyncPipe],
template: `
<p>With the async pipe: {{ seconds$ | async }}</p>
<p>With a signal: {{ seconds() }}</p>
`,
})
export class FlashSale {
private readonly analytics = inject(Analytics);
// 1. The async pipe subscribes and unsubscribes for you.
readonly seconds$ = interval(1000);
// 2. toSignal unsubscribes when the component is destroyed.
readonly seconds = toSignal(interval(1000), { initialValue: 0 });
constructor() {
// 3. A manual subscribe for a side effect, closed on destroy.
interval(30_000)
.pipe(takeUntilDestroyed())
.subscribe(() => this.analytics.track('sale-banner-seen'));
}
}
- The async pipe is for showing a value in the template. When the component is destroyed, it unsubscribes by itself.
- The toSignal function turns an observable into a signal. You must call it in an injection context (a field initializer or the constructor). When the component is destroyed, the subscription is closed.
- The takeUntilDestroyed function is for a manual subscribe. Without an argument it only works in an injection context. Anywhere else, like ngOnInit, you must give it a DestroyRef.
The operators that matter
For search, this chain is almost standard:
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, debounceTime, distinctUntilChanged, filter, map, of, switchMap } from 'rxjs';
import { Product } from './product';
@Component({
selector: 'app-product-search',
imports: [ReactiveFormsModule],
template: `
<input [formControl]="query" placeholder="Search products" />
@for (p of results(); track p.id) {
<p>{{ p.name }}</p>
}
`,
})
export class ProductSearch {
private readonly http = inject(HttpClient);
readonly query = new FormControl('', { nonNullable: true });
readonly results = toSignal(
this.query.valueChanges.pipe(
map(q => q.trim()),
filter(q => q.length >= 2),
debounceTime(300),
distinctUntilChanged(),
switchMap(q =>
this.http.get<Product[]>('/api/products', { params: { q } }).pipe(
catchError(() => of([])),
),
),
),
{ initialValue: [] },
);
}
- The map operator changes each value. Here it removes spaces at the start and the end.
- The filter operator drops values that fail a test. A one-letter search does not go out.
- The debounceTime operator waits until the user stops typing for 300 ms. Then it sends only the last value.
- The distinctUntilChanged operator drops a value that is the same as the one before. For example, the user deletes a letter and types it again.
- The switchMap operator makes one request for each word. When a new word arrives, it cancels the old request. So an old response never covers a new one.
- The catchError operator is inside switchMap, not outside it. If it were outside, the first error would end the whole stream and the search box would stop working.
Which map operator?
All four operators make an inner observable for each value. The difference is what they do when a new value arrives and the old work is not finished yet:
| Operator | Old work not finished, a new value arrives | Shop example |
|---|---|---|
| switchMap | Cancels the old one and starts the new one. | The search box |
| mergeMap | Runs both in parallel. | Loading the stock of several products at once |
| concatMap | Puts the new one in a queue and runs them in order. | Saving quantity changes in the cart, in the same order |
| exhaustMap | Ignores the new one. | A “Place order” button clicked twice |
For the place-order button, exhaustMap stops a duplicate order on the client:
private readonly placeOrder$ = new Subject<OrderRequest>();
readonly order = toSignal(
this.placeOrder$.pipe(
exhaustMap(request =>
this.http.post<Order>('/api/orders', request).pipe(
catchError(() => of(null)),
),
),
),
);
submit(request: OrderRequest) {
this.placeOrder$.next(request);
}
This is only client-side protection. The server must also stop duplicate orders, for example with an idempotency key.
Signals or RxJS?
- Signals are for state: a value that always has a current value. The cart, the selected filter, the signed-in user.
- RxJS is for events over time: typing, clicks, WebSocket messages. Wherever time matters (debounce, cancel, queue, retry), RxJS is the better tool.
- Two bridge functions connect them. The toSignal function turns an observable into a signal. The toObservable function turns a signal into an observable.
readonly query = signal('');
readonly results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
switchMap(q => this.http.get<Product[]>('/api/products', { params: { q } })),
),
{ initialValue: [] },
);
Change detection
After each change, Angular must find out which parts of the page to update. It does this by “checking” components: it computes the template expressions again, and if a result changed, it updates the DOM.
- In the default mode, with zone.js, after every event, timer or HTTP response anywhere in the app, Angular checks all components from top to bottom.
- In OnPush mode, Angular skips a component and its children, unless that component is marked “dirty”.
What marks an OnPush component dirty?
- An input with a new reference. The comparison is by reference, like ===. A new object or array means a change. The same object with changed content means no change.
- An event in the component’s own template (or its children), like a click.
- The async pipe when it gets a new value.
- A signal the template reads whose value changed.
- A manual call to the markForCheck method of ChangeDetectorRef.
Why changing an input array does not work
@Component({
selector: 'app-cart-summary',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ items().length }} items in your cart</p>`,
})
export class CartSummary {
readonly items = input.required<CartItem[]>();
}
@Component({
selector: 'app-shop',
imports: [CartSummary],
template: `
<button (click)="add()">Add shoes</button>
<app-cart-summary [items]="items" />
`,
})
export class Shop {
items: CartItem[] = [];
add() {
const shoes = { productId: 7, name: 'Shoes', price: 50, quantity: 1 };
this.items.push(shoes); // same array: CartSummary is skipped
// this.items = [...this.items, shoes]; // new array: CartSummary updates
}
}
- The push method changes the same array. The reference stays the same.
- When Angular checks the input, it compares the new value with the old one by reference, like ===. The result is “equal”, so the input did not change.
- The OnPush component is not marked dirty and is skipped. The old number stays on the page.
- The right way is to always make a new array or object, or to keep the state in a signal and use the update method.
Zoneless apps
The zone.js library patches browser functions like setTimeout and events so Angular learns “something may have changed”. In zoneless mode, this library is gone. Angular only works when it is told directly:
- A signal that a template reads changes.
- An event happens in a template.
- The async pipe or markForCheck is called.
- An input gets a new value.
import { provideZonelessChangeDetection } from '@angular/core';
bootstrapApplication(App, {
providers: [provideZonelessChangeDetection(), provideRouter(routes)],
});
This mode is stable since Angular 20.2. Since Angular 21, new apps made with the CLI are zoneless by default. Important: if you change a plain field inside setTimeout or inside a subscribe callback, a zoneless page does not update. Keep such values in signals.
Function calls in templates
Any function called in a template runs again on every check of that component. In the default mode, that means after every click or timer anywhere in the app.
// Bad: filters and sorts 5,000 products on every check.
visibleProducts() {
return this.products()
.filter(p => p.name.includes(this.term()))
.sort((a, b) => a.price - b.price);
}
// Good: runs again only when products or term change.
readonly visibleProducts = computed(() =>
this.products()
.filter(p => p.name.includes(this.term()))
.sort((a, b) => a.price - b.price),
);
Reading a signal or a computed in a template is fine. It is very fast, because a computed keeps its result. The problem is plain functions that do heavy work.
Common mistakes
| Mistake | Result | The right way |
|---|---|---|
| A subscribe inside another subscribe | Responses out of order. Nothing is cancelled. | Use switchMap or another map operator. |
| A subscription that is never closed | A memory leak. Code runs after the user leaves the page. | The async pipe, toSignal or takeUntilDestroyed. |
| Two async pipes on one HTTP request | Two requests to the server. | Subscribe once, or use shareReplay. |
| catchError outside switchMap | The first error ends the whole stream. | Put catchError on the inner observable. |
| mergeMap for search | An old response may cover a new one. | switchMap. |
| Changing the input array of an OnPush child | The child does not update. | Make a new array or use a signal. |
| A heavy function in the template | It runs again on every check. | Use computed. |
Summary in 8 lines
- An observable is lazy, gives many values and can be cancelled. A promise starts right away and has one value.
- HttpClient gives a cold observable. Each subscribe is a new request.
- Close every subscription: the async pipe, toSignal or takeUntilDestroyed.
- For search use debounceTime, distinctUntilChanged and switchMap. For the place-order button use exhaustMap. When the order matters, use concatMap.
- Put catchError inside the map operator so the main stream stays alive.
- Signals are for state and RxJS is for events over time. toSignal and toObservable connect them.
- An OnPush component is checked only for a new input, its own event, the async pipe or a signal change. So do not change an input, make a new one.
- In zoneless mode (stable since Angular 20.2), only signals, events and markForCheck update the page.