Order statuses in a delivery app don't arrive all at once. Processing, then cooking, then delivering, one at a time, sometimes minutes apart.
RxJS is made for data like this. RxJS is a library (a set of ready-made code) for handling data that arrives bit by bit over time. Angular uses it in many places: HttpClient, the router and forms. Its main type is the Observable: a stream of values you can listen to. Picture the order status notifications from Jali's Pancake Stall. Notifications only arrive after you switch on a subscription, and they stop when you switch it off. If you forget to switch it off, your phone keeps buzzing even after you've left the page. In RxJS, that stream of notifications is an Observable, switching on the subscription is subscribing, and switching it off is unsubscribing.
Observable and subscribe
This Observable sends three statuses, then completes:
import { Observable } from 'rxjs'
const status$ = new Observable<string>((subscriber) => {
console.log('kitchen starts')
subscriber.next('processing')
subscriber.next('cooking')
subscriber.next('delivering')
subscriber.complete()
})
status$.subscribe({
next: (s) => console.log('status:', s),
complete: () => console.log('done'),
})
// kitchen starts / status: processing / status: cooking / status: delivering / done
new Observable(fn)stores a function that produces values. Inside it,subscriberis whoever subscribes.next(value)sends one value to the subscriber.complete()marks the stream finished, anderror(err)marks it failed.subscribe()starts listening. You can give it one function (subscribe((s) => ...)), or an object holdingnext,errorandcomplete, or only some of them, as in this code.- The
$at the end of the namestatus$is only a naming habit. It means "this is an Observable".
No subscribe, no run
The function inside an Observable only runs when someone subscribes. Without subscribe(), kitchen starts prints 0 times and no status is sent. That is why Observables are called lazy.
And each subscribe() runs that function again from the start:
| What's written | kitchen starts prints |
|---|---|
status$ created, never subscribed |
0 times |
status$.subscribe(...) once |
once, then 3 statuses |
status$.subscribe(...) twice |
twice, 3 statuses each |
This matters in the next lesson, HTTP Client: an HttpClient request (asking a server for data) is an Observable too, so the request is only sent when it's subscribed.
Making Observables: of, from, timer
RxJS has ready-made functions for making Observables:
| Creator | What it sends |
|---|---|
of(10, 8) |
10, then 8, right away, then completes |
from([4, 6, 0]) |
4, 6, 0 (the array's items one by one), then completes |
interval(1000) |
0, 1, 2, ... every second, never completes |
timer(0, 2000) |
0 right away, then 1, 2, ... every 2 seconds, never completes |
of and from send everything right away, inside subscribe(). interval and timer keep going until unsubscribed.
pipe, map, filter
An operator is a function that works on each value passing through. Operators go inside pipe(), and the source Observable doesn't change. This RxJS pipe() is different from the | pipe in templates from the Angular Pipes lesson, even though the name is the same. In this code, the numbers are the stock of three menu items:
import { from, filter, map } from 'rxjs'
from([4, 6, 0])
.pipe(
filter((stock) => stock > 0),
map((stock) => stock * 10),
)
.subscribe((n) => console.log(n))
// 40
// 60
filteronly passes on values that meet the condition (stock > 0). Stock 0 (the sold-out Pandan Pancake) is dropped.mapturns each value into a new one, here the stock times 10.tapruns something for each passing value (aconsole.log, for example) without changing it.- Operators are imported from
'rxjs'. The older form,'rxjs/operators', still works too.
Jali's order status is made the same way. The app asks the kitchen every 2 seconds, and map turns each number from timer into a status:
const STEPS = ['processing', 'cooking', 'delivering']
status$ = timer(0, 2000).pipe(map((i) => STEPS[Math.min(i, 2)]))
// second 0: processing, second 2: cooking, second 4: delivering, second 6: delivering, ...
In the exercise, the pattern is the same, with one value. In the constructor, you write of('angular').pipe(map((val) => val.toUpperCase())).subscribe((val) => (this.result = val)). So <p>{{ result }}</p> reads ANGULAR.
Unsubscribe, or memory leaks
The timer above never completes. Say the Order component calls subscribe() itself in its class, then is removed from the page (for example, App hides it with @if). Its subscription stays alive: every 2 seconds its callback (the function you gave to subscribe) runs for a component that's gone. If Order is shown and removed five times, five subscriptions run at the same time. That's called a memory leak: memory stays in use for things nobody needs any more. The code below shows one way that leaks and two safe ways:
// Leaks: Angular calls ngOnInit once after the component is created.
ngOnInit() {
this.status$.subscribe((s) => (this.status = s))
}
// Safe 1: keep the subscription, switch it off in ngOnDestroy
private subscription?: Subscription
ngOnInit() {
this.subscription = this.status$.subscribe((s) => (this.status = s))
}
ngOnDestroy() {
this.subscription?.unsubscribe()
}
// Safe 2: takeUntilDestroyed() from '@angular/core/rxjs-interop', written in the constructor
constructor() {
this.status$.pipe(takeUntilDestroyed()).subscribe((s) => (this.status = s))
}
In safe way 1, ngOnDestroy is a method Angular calls once, right before the component is removed. In safe way 2, takeUntilDestroyed() stops the subscription by itself when the component is removed.
One more thing about this.status = s: since Angular 22, components are OnPush by default (a component is only redrawn when something tells it to). So if a plain property is replaced inside subscribe, the view doesn't change. In Angular 22, keep the value in a signal (status = signal(''), then this.status.set(s)), or let the template subscribe (with the async pipe, below). There's also status = toSignal(this.status$) from @angular/core/rxjs-interop, which subscribes by itself, keeps each value in a signal, and unsubscribes by itself when the component is removed.
The third safe way to unsubscribe, and the shortest, is the async pipe.
The async pipe: automatic subscribe and unsubscribe
The async pipe from the Angular Pipes lesson subscribes from the template:
import { Component } from '@angular/core'
import { AsyncPipe } from '@angular/common'
import { map, timer } from 'rxjs'
const STEPS = ['processing', 'cooking', 'delivering']
@Component({
selector: 'app-order',
standalone: true,
imports: [AsyncPipe],
template: `<p>Status: {{ status$ | async }}</p>`,
})
export class Order {
status$ = timer(0, 2000).pipe(map((i) => STEPS[Math.min(i, 2)]))
}
async subscribes when the component appears, shows each new value (Status: processing, then cooking, then delivering), and unsubscribes by itself when the component is removed. There's no subscribe() in the class, and nothing to switch off.
📌 Subject and BehaviorSubject
A Subject is an Observable whose values you send yourself with next(). The difference between Subject and BehaviorSubject shows with a late subscriber, one who subscribes after a value was sent:
const status = new BehaviorSubject('processing')
status.next('cooking')
status.subscribe((s) => console.log('late:', s)) // late: cooking
- A
BehaviorSubjecthas a starting value and gives the last value to a new subscriber, right when it subscribes. You can also read it withstatus.value. - A plain
Subjectkeeps nothing: a late subscriber only gets values sent after it subscribed. The same code withnew Subject<string>()prints nothing.
⚠️ Subscriptions never switched on, or never switched off
- Forgetting to subscribe. An Observable nobody subscribes to runs nothing: no log, no request.
- A manual subscribe with no unsubscribe. For a stream that never completes (
interval, a repeatingtimer), the subscription stays alive after its component is removed. Useasync,takeUntilDestroyed(), orunsubscribe()inngOnDestroy. - An Observable in the template without
async.{{ status$ }}shows[object Object]. With| asyncbut noAsyncPipeinimports, Order doesn't show and the console writesNG0302: The pipe 'async' could not be found in the 'Order' component. Verify that it is included in the '@Component.imports' of this component. - Exercise detail. The upper-casing happens inside
pipe(map(...)), and the value coming out is caught throughsubscribe((val) => (this.result = val)). Typing'ANGULAR'straight intoresultisn't accepted.
TL;DR: An Observable, the main type of the RxJS library, is a stream of values that arrive over time. subscribe() starts listening to that stream. Nothing runs without a subscribe, and each subscribe runs the Observable from the start. of and from send values that already exist and then complete, while interval and timer keep going. pipe(filter(...), map(...)) filters and changes each value passing through. A subscription to a stream that never completes must be stopped (unsubscribe) when the component is removed, or memory leaks. The shortest way: {{ status$ | async }} in the template (plus AsyncPipe in imports). status$ is the Observable, and the async pipe subscribes and unsubscribes automatically. Another way: takeUntilDestroyed(). A BehaviorSubject, an Observable whose values you send yourself, gives its last value to a subscriber who arrives late. A plain Subject doesn't.
⚡ An Observable runs only once subscribed
Write:
const status$ = new Observable<string>((subscriber) => {
console.log('kitchen starts')
subscriber.next('processing')
subscriber.complete()
})
status$.subscribe((s) => console.log('status:', s))
Guess first: the subscribe line is deleted. How many times does kitchen starts print?
0 times. The function inside an Observable only runs when someone subscribes, and each subscribe() runs it again from the start.
Meaning: An Observable is a stream of values that arrive over time. next() sends one value to the subscriber (whoever subscribes), and complete() marks the stream finished. subscribe() starts listening.
⚡ pipe, filter, map
Write:
from([4, 6, 0])
.pipe(
filter((stock) => stock > 0),
map((stock) => stock * 10),
)
.subscribe((n) => console.log(n))
// 40
// 60
Meaning: from([4, 6, 0]) sends the array's items one by one. filter and map are operators: functions inside pipe() that work on each value passing through. filter only passes on values that meet the condition, so stock 0 is dropped. map turns each value into a new one, here times 10.
In the exercise, the text 'angular' is turned into capital letters inside pipe(map(...)), then the result is caught with subscribe((val) => (this.result = val)).
⚡ async: automatic subscribe and unsubscribe
Write:
imports: [AsyncPipe],
template: `<p>Status: {{ status$ | async }}</p>`,
Meaning: status$ is an Observable that sends the order's status. The async pipe subscribes when the component appears, shows each new value, then unsubscribes by itself when the component is removed. If you subscribe by hand to a stream that never completes, like timer or interval (which send a number every few seconds), you have to stop it yourself. Otherwise the subscription keeps running after the component is removed, and memory leaks.