Sub topic 10
Understanding Observables and RxJS basics
This chapter assumes you have finished the signals and services chapters. It also assumes you can read TypeScript generics and arrow functions. Next chapter, HttpClient returns Observables. Here you learn how they behave first.
What an Observable is
An Observable is an object that describes a stream of values over time. It can emit zero or more values, then either complete or fail with an error. RxJS is the library that provides Observables and the functions that transform them. Angular depends on it, so it is already installed in your project.
A signal always holds a current value that you read by calling it. An Observable holds nothing. It only delivers values to whoever is listening. That makes Observables a good fit for events that arrive later, such as an HTTP response.
Observables are lazy
Creating an Observable does not run it. The work starts only when someone calls subscribe(). Each subscription runs the work again. This is why the TaskApi methods in the HTTP chapter send nothing until a caller subscribes.
import { Observable } from 'rxjs';
const numbers$ = new Observable<number>(subscriber => {
console.log('started');
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
});
numbers$.subscribe({
next: value => console.log('got', value),
complete: () => console.log('done'),
});
numbers$.subscribe(value => console.log('second subscriber', value));The output shows started twice, once per subscription. The trailing $ in numbers$ is a naming convention for Observables, not syntax.
Transforming values with pipe
Operators are functions that you chain inside pipe(). Each operator receives the stream and returns a new one. The original Observable is unchanged.
import { of } from 'rxjs';
import { filter, map } from 'rxjs/operators';
interface Task {
id: number;
title: string;
done: boolean;
}
const tasks$ = of<Task[]>([
{ id: 1, title: 'Write tests', done: true },
{ id: 2, title: 'Ship it', done: false },
]);
tasks$
.pipe(
map(list => list.filter(t => !t.done)),
filter(open => open.length > 0),
)
.subscribe(open => console.log(open.length, 'open task(s)'));Here map changes each emitted value, and filter drops values that fail a test. In the HTTP chapter you will use map to reshape server data and catchError to handle failures.
Using Observables in components
Subscribing by hand creates a duty to unsubscribe. A long-lived stream keeps running after its component is destroyed, which leaks memory. Angular offers two ways to avoid this.
The first converts an Observable to a signal. toSignal subscribes right away and unsubscribes when the component is destroyed.
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { TaskApi } from './task.api';
@Component({
selector: 'app-remote-count',
template: `<p>{{ tasks().length }} tasks from the server</p>`,
})
export class RemoteCountComponent {
private readonly api = inject(TaskApi);
readonly tasks = toSignal(this.api.getTasks(), { initialValue: [] });
}The initialValue matters. Without it, the signal type includes undefined until the first emission.
The second keeps a manual subscription but ends it automatically with takeUntilDestroyed(). Call it in a constructor or field initializer, where Angular has an injection context.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Never calling `subscribe()` | No request is sent | Subscribe, or use `toSignal` or the `async` pipe |
| Subscribing inside another `subscribe()` | Tangled, hard-to-cancel code | Combine them with an operator such as `switchMap` |
| Forgetting to unsubscribe from a long-lived stream | Memory leak, duplicate updates | Use `takeUntilDestroyed()` or `toSignal` |
| Subscribing twice to one HTTP Observable | Two requests sent | Subscribe once and share the result |
Exercise
You write const request$ = this.http.post<Task>('/api/tasks', { title }); and call request$.subscribe() twice. How many requests are sent, and what would send none?
Show answer
Two requests are sent, because each subscription runs the Observable again. If you never call subscribe(), no request is sent, because Observables are lazy.
Exercise
Why does toSignal(this.api.getTasks(), { initialValue: [] }) need no manual cleanup?
Show answer
toSignal subscribes when it is called and unsubscribes automatically when the component or service that created it is destroyed.