Sub topic 1
What an Observable Is: Producers, Observers, and Subscriptions
Angular uses observables throughout its APIs. HttpClient returns them, reactive forms emit them, and the router exposes route data through them. Before you can use any of those features well, you need a clear picture of what an observable actually does when you subscribe to it. This chapter builds that picture from the ground up with a hand-written observable, and then covers the rules every observable follows.
Prerequisites
This chapter assumes you are comfortable with:
- TypeScript fundamentals, including generics (
Observable<number>) and arrow functions. - Asynchronous JavaScript: callbacks,
setTimeout,setInterval, and Promises. - Running a TypeScript file with Node, for example with
npx tsx file.tsafternpm install rxjs.
Angular knowledge is not needed for this chapter. Every example here runs in plain Node.
The Three Roles
An observable system has three parts. Keep them separate in your head, because most confusion about RxJS comes from mixing them up.
| Role | What it is | In RxJS |
|---|---|---|
| Producer | The source of values: a timer, a DOM event, an HTTP response | The function you pass to `new Observable(...)` |
| Observer | The consumer that reacts to values | An object with `next`, `error`, and `complete` callbacks |
| Subscription | The live connection between the two | The object returned by `subscribe()`, with an `unsubscribe()` method |
The Observable itself is none of these. It is a blueprint: a description of how to connect a producer to an observer. No work happens until someone subscribes.
A Hand-Built Observable
Here is an observable that emits an increasing number every second:
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);Run it and you see 0, 1, 2, and then the program exits. Here is what each piece does:
new Observable<number>(subscriber => { ... })stores the function. The function is not called yet.ticks$.subscribe(observer)calls the function and passes in asubscriber, which wraps your observer.- Inside the function, the producer (the interval) calls
subscriber.next(...)to push values. - The function returns a teardown function. RxJS runs it when the subscription ends.
sub.unsubscribe()at 3.5 seconds runs the teardown, which clears the interval.
Notice that done is never printed. Unsubscribing is the consumer saying "I no longer care." It is not the producer saying "I am finished." Only subscriber.complete() triggers the complete callback.
The $ suffix on ticks$ is a naming convention for variables that hold observables. RxJS does not require it, but Angular code uses it widely.
Observables Are Lazy
Because the producer function only runs on subscribe, an observable with no subscribers does nothing. You can see this, and the order of execution, with a synchronous example:
import { Observable } from 'rxjs';
const numbers$ = new Observable<number>(subscriber => {
console.log('producer started');
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
subscriber.next(3); // ignored: the stream has already completed
});
console.log('before subscribe');
numbers$.subscribe({
next: value => console.log('next', value),
complete: () => console.log('complete'),
});
console.log('after subscribe');The output is:
before subscribe
producer started
next 1
next 2
complete
after subscribeThis shows two things that surprise people:
- Observables are not asynchronous by default. This producer emits synchronously, so all its values arrive before
subscribe()returns. An observable is only asynchronous when its producer is, as withsetIntervalabove. - After
complete(), further calls tonext()are silently dropped. The subscriber enforces the contract for you.
Each Subscription Runs Its Own Producer
Subscribing twice runs the producer function twice. Each observer gets its own independent execution.
import { Observable } from 'rxjs';
let executions = 0;
const random$ = new Observable<number>(subscriber => {
executions++;
subscriber.next(Math.round(Math.random() * 100));
subscriber.complete();
});
random$.subscribe(value => console.log('A got', value));
random$.subscribe(value => console.log('B got', value));
console.log('producer ran', executions, 'times');Subscribers A and B usually print different numbers, and the counter reads 2. This behavior is called a cold observable. It matters in Angular: subscribing twice to an HttpClient observable sends two HTTP requests. A later chapter covers hot observables and shareReplay, which let several subscribers share one execution.
Also note that subscribe accepts a single function as shorthand for { next: fn }.
The Observable Contract
Every observable follows the same grammar for what it may emit:
- Zero or more
nextnotifications, then - At most one terminal notification: either
errororcomplete, never both.
After a terminal notification, or after unsubscribe(), the subscription is closed and the teardown runs. A stream may also never terminate, like ticks$, which keeps going until the consumer unsubscribes.
Errors End the Stream
An error is terminal. The stream does not continue after it:
import { Observable } from 'rxjs';
const failing$ = new Observable<number>(subscriber => {
subscriber.next(1);
subscriber.error(new Error('boom'));
subscriber.next(2); // ignored
return () => console.log('teardown');
});
failing$.subscribe({
next: value => console.log('next', value),
error: err => console.log('error:', err.message),
complete: () => console.log('complete'), // never called
});The output is next 1, error: boom, teardown.
If the producer function itself throws, RxJS catches the exception and delivers it as an error notification, so it follows the same path.
Teardown and Subscriptions in Detail
The teardown function is where a producer releases its resources: it clears timers, removes event listeners, and aborts requests. RxJS guarantees teardown runs exactly once, whichever way the subscription ends.
A Subscription also supports a few other operations:
sub.closedistrueonce the subscription has ended.sub.add(otherSub)groups subscriptions so that a singleunsubscribe()closes them all.- Calling
unsubscribe()on an already closed subscription is harmless.
import { Observable } from 'rxjs';
const timer$ = (label: string) =>
new Observable<string>(subscriber => {
const id = setInterval(() => subscriber.next(label), 500);
return () => {
clearInterval(id);
console.log(label, 'cleaned up');
};
});
const parent = timer$('A').subscribe(v => console.log(v));
parent.add(timer$('B').subscribe(v => console.log(v)));
setTimeout(() => {
parent.unsubscribe();
console.log('closed?', parent.closed);
}, 1200);Both intervals stop and both cleanup messages print. In Angular, a component that subscribes and never unsubscribes leaves its producer running after the component is destroyed. That is a memory leak. A later chapter shows the Angular tools that handle this for you: the async pipe and takeUntilDestroyed.
Observables Compared with Promises
You already know Promises, so the differences are worth spelling out.
| Aspect | Promise | Observable |
|---|---|---|
| Start | Eager: runs when created | Lazy: runs on subscribe |
| Values | Exactly one | Zero to many |
| Timing | Always asynchronous callbacks | Synchronous or asynchronous, depending on the producer |
| Cancellation | Not built in | `unsubscribe()` runs teardown |
| Sharing | One execution shared by every `.then` | One execution per subscriber (cold) by default |
| Composition | `.then` chains | `pipe` with operators |
Common Mistakes
- Expecting work without subscribing. Calling
http.get(...)and never subscribing sends no request. - Treating unsubscribe as completion. Cleanup belongs in teardown, not in the
completecallback, becausecompletenever fires when the consumer unsubscribes. - Forgetting the teardown. A producer that starts a timer or listener but returns nothing keeps running after unsubscribe.
- Assuming asynchrony. Code after
subscribe()may run after every value has already arrived. - Subscribing twice by accident. Each subscription to a cold observable repeats the work, including network calls.
Exercise
In the ticks$ example, change the setTimeout delay to 2500 ms. What gets logged, and does "done" appear? Explain why.
Show answer
The output is 0 and 1. Values arrive at 1000 ms and 2000 ms, and the unsubscribe at 2500 ms runs the teardown, which clears the interval. "done" does not appear because unsubscribing does not send a complete notification. Only the producer calling subscriber.complete() triggers it.
Exercise
Write an observable countdown$(n) that emits n, n-1, ..., 1 once per second and then completes. Make sure unsubscribing early stops the timer.
Show answer
function countdown$(n: number) { return new Observable<number>(subscriber => { let current = n; const id = setInterval(() => { subscriber.next(current--); if (current === 0) subscriber.complete(); }, 1000); return () => clearInterval(id); }); } The teardown clears the interval both when the stream completes and when a consumer unsubscribes early.
Exercise
A component calls this.http.get('/api/users') and subscribes to the result in two places. How many HTTP requests are sent, and why?
Show answer
Two requests. HttpClient observables are cold, so each subscription runs the producer function again and each run sends its own request.