Sub topic 1
What an Observable Is: Producers, Observers, and Subscriptions
Prerequisites
This chapter assumes you know TypeScript generics and arrow functions, Angular standalone components and dependency injection, and how Promises work.
Producers, Observers, and Subscriptions
An observable is a lazy producer of values over time. It does nothing until something subscribes to it. The observer is an object with next, error, and complete callbacks. The subscription is the handle that subscribe returns, and you call unsubscribe() on it to stop receiving values.
import { Observable } from 'rxjs';
const ticks$ = new Observable<number>(subscriber => {
let count = 0;
const id = setInterval(() => subscriber.next(count++), 1000);
return () => clearInterval(id);
});
const sub = ticks$.subscribe({
next: value => console.log(value),
complete: () => console.log('done'),
});
setTimeout(() => sub.unsubscribe(), 3500);This logs 0, 1, and 2. When unsubscribe() runs, the observable calls the teardown function it returned, which clears the interval. The complete callback never runs because the stream was cancelled, not completed.
Creation Functions
You will rarely call new Observable yourself. RxJS provides creation functions for common sources:
| Function | Emits |
|---|---|
| `of(1, 2, 3)` | Its arguments, then completes |
| `from([1, 2])` or `from(promise)` | Array items or a Promise result |
| `fromEvent(el, 'click')` | DOM events, never completes |
| `interval(1000)` | 0, 1, 2… every second, never completes |
Transforming with pipe
pipe chains operators. Each operator returns a new observable and leaves the source unchanged.
import { interval, filter, map, tap, take } from 'rxjs';
interval(500)
.pipe(
filter(n => n % 2 === 0),
map(n => n * 10),
tap(v => console.log('debug', v)),
take(3)
)
.subscribe(v => console.log(v));tap runs side effects such as logging without changing the values. take(3) completes the stream after three values.
Avoiding Memory Leaks
A subscription to a stream that never completes, such as interval or fromEvent, keeps running after its component is destroyed. In Angular, call takeUntilDestroyed() inside an injection context, for example the constructor:
import { Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({ selector: 'app-clock', standalone: true, template: `{{ seconds }}` })
export class ClockComponent {
seconds = 0;
constructor() {
interval(1000).pipe(takeUntilDestroyed()).subscribe(n => (this.seconds = n));
}
}The async Pipe
The async pipe subscribes for you and unsubscribes when the component is destroyed. You don't need to write any cleanup code.
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { interval, map } from 'rxjs';
@Component({
selector: 'app-timer',
standalone: true,
imports: [AsyncPipe],
template: `<p>{{ elapsed$ | async }}s</p>`,
})
export class TimerComponent {
elapsed$ = interval(1000).pipe(map(n => n + 1));
}Exercise
A component subscribes to fromEvent(window, 'resize') in its constructor with no cleanup. What goes wrong when the user navigates away, and what are two ways to fix it?
Show answer
The subscription keeps running after the component is destroyed, so the handler leaks memory and keeps firing on resize. Fix it by adding takeUntilDestroyed() to the pipe, or by exposing the stream as a property and rendering it with the async pipe.