RxJS Basics
RxJS is a library for working with streams of values over time. Angular uses it in several places — HttpClient responses, router events, valueChanges of form controls — so you need to know the basics even in a signal-first app.
Observables in one paragraph
An Observable is a lazy producer of values. Nothing happens until you subscribe. Once subscribed, it can deliver any number of values (next), then either fail (error) or finish (complete). Subscribing returns a Subscription you can unsubscribe() from.
| Promise | Observable | Signal | |
|---|---|---|---|
| Values | Exactly one | Zero to many, over time | Always has a current value |
| Starts | Immediately | On subscribe (lazy) | — (it's state, not a process) |
| Cancel | No | unsubscribe() |
— |
| Best for | One-off async results | Events, streams, HTTP | UI state |
Build a tiny Observable
The idea is small enough to implement yourself. This plain TypeScript version supports subscribers, completion, unsubscribing and a pipe with map and filter operators:
interface Observer<T> { next: (v: T) => void; complete?: () => void; }
type Operator<A, B> = (src: Observable<A>) => Observable<B>;
class Observable<T> {
constructor(private producer: (o: Observer<T>) => () => void) {}
subscribe(o: Observer<T>) {
let closed = false;
const teardown = this.producer({
next: (v) => { if (!closed) o.next(v); },
complete: () => { if (!closed) { closed = true; o.complete?.(); } },
});
return { unsubscribe: () => { closed = true; teardown(); } };
}
pipe<B>(op: Operator<T, B>): Observable<B> { return op(this); }
}
const map = <A, B>(fn: (a: A) => B): Operator<A, B> => (src) =>
new Observable((o) => src.subscribe({ next: (v) => o.next(fn(v)), complete: o.complete }).unsubscribe);
const filter = <A>(pred: (a: A) => boolean): Operator<A, A> => (src) =>
new Observable((o) => src.subscribe({ next: (v) => { if (pred(v)) o.next(v); }, complete: o.complete }).unsubscribe);
const of = <T>(...values: T[]) => new Observable<T>((o) => {
console.log('producer started');
values.forEach((v) => o.next(v));
o.complete?.();
return () => {};
});
const prices$ = of(5, 12, 8, 30);
console.log('nothing has run yet');
prices$
.pipe(filter((p: number) => p >= 8))
.pipe(map((p: number) => `${p.toFixed(2)}`))
.subscribe({ next: (v) => console.log('got', v), complete: () => console.log('done') });nothing has run yet
producer started
got $12.00
got $8.00
got $30.00
done
Notice the laziness: producer started appears only after subscribe. Real RxJS works the same way, with a single pipe(op1, op2, …) call taking any number of operators.
Common operators
| Operator | What it does |
|---|---|
map(fn) |
Transform each value |
filter(pred) |
Let only matching values through |
tap(fn) |
Run a side effect (e.g. logging) without changing values |
debounceTime(ms) |
Emit only after the source has been quiet for ms |
distinctUntilChanged() |
Skip values equal to the previous one |
switchMap(fn) |
Map to a new Observable, cancelling the previous one |
catchError(fn) |
Replace an error with a fallback Observable |
takeUntilDestroyed() |
(Angular) Unsubscribe automatically when the component is destroyed |
A search box with RxJS
The classic RxJS use case: search as the user types, but don't fire a request on every keystroke, and ignore stale responses:
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { debounceTime, distinctUntilChanged, filter, switchMap } from 'rxjs';
import { CityApi } from './city-api';
@Component({
selector: 'app-city-search',
imports: [ReactiveFormsModule],
template: `
<input [formControl]="query" placeholder="Search cities…" />
<ul>
@for (c of results(); track c) { <li>{{ c }}</li> }
</ul>
`,
})
export class CitySearch {
private api = inject(CityApi);
query = new FormControl('', { nonNullable: true });
results = toSignal(
this.query.valueChanges.pipe(
debounceTime(300), // wait for a typing pause
distinctUntilChanged(), // ignore unchanged text
filter((q) => q.length >= 2), // need at least 2 letters
switchMap((q) => this.api.search(q)), // cancel older requests
),
{ initialValue: [] as string[] },
);
}Subjects: Observables you push into
A Subject is both an Observable and an Observer: you call next() on it, and every subscriber receives the value. A BehaviorSubject also remembers the latest value and gives it to new subscribers immediately — similar to a signal:
class BehaviorSubject<T> {
private subscribers: ((v: T) => void)[] = [];
constructor(private current: T) {}
next(v: T) {
this.current = v;
this.subscribers.forEach((s) => s(v));
}
subscribe(fn: (v: T) => void) {
this.subscribers.push(fn);
fn(this.current); // replay the latest value
}
get value() { return this.current; }
}
const user$ = new BehaviorSubject('guest');
user$.subscribe((u) => console.log('header sees:', u));
user$.next('mai');
user$.subscribe((u) => console.log('sidebar sees:', u)); // late subscriber
user$.next('linh');
console.log('current value:', user$.value);header sees: guest
header sees: mai
sidebar sees: mai
header sees: linh
sidebar sees: linh
current value: linh
RxJS and signals together
@angular/core/rxjs-interop bridges the two worlds:
| Function | Converts |
|---|---|
toSignal(obs$, { initialValue }) |
Observable → Signal (subscribes and unsubscribes for you) |
toObservable(sig) |
Signal → Observable |
takeUntilDestroyed() |
Ends a subscription when the component/service is destroyed |
Tip: Use signals for state the template reads, and RxJS for event streams that need timing operators like
debounceTimeor cancellation viaswitchMap.
Test yourself
When does a cold Observable start producing values?
- When it is created
- When it is subscribed to
- When
complete()is called - At application startup
Which operator cancels the previous inner request when a new search term arrives?
- map
- mergeMap
- switchMap
- tap
What does a BehaviorSubject give a new subscriber immediately?
- Nothing
- All past values
- The latest (current) value
- An error