Sub topic 1
What an Observable Is: Producers, Observers, and Subscriptions
Angular hands you observables from many places: HttpClient, reactive forms, and the router. This chapter covers the model behind all of them. An observable is a function that sets up a producer. The producer pushes values to an observer, and a subscription lets you stop it.
Prerequisites
This chapter assumes you know:
- TypeScript generics and arrow functions
- Asynchronous JavaScript with callbacks and Promises
- How to install and import an npm package (
rxjscomes with every Angular project)
The Three Parts
| Part | What it is | Who provides it |
|---|---|---|
| Producer | The code that creates values, such as a timer, a socket, or a request | The observable's subscribe function |
| Observer | An object with `next`, `error`, and `complete` callbacks | You, when you call `subscribe` |
| Subscription | A handle returned by `subscribe`, with an `unsubscribe()` method | RxJS |
An observable is lazy. Creating one runs nothing. The producer starts only when something subscribes. Each new subscriber also gets its own run of the producer. A Promise works differently: it starts as soon as it is created and shares one result with everyone who awaits it.
A Hand-Built Observable
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);Here is what happens when this runs:
new Observable(...)stores the function. No interval exists yet.subscribe(...)calls that function with asubscriber. The subscriber wraps your observer. The interval starts.- Every second,
subscriber.nextsends a value to yournextcallback, so0,1, and2are printed. - At 3.5 seconds,
unsubscribe()runs the teardown function the producer returned, and the interval is cleared.
The $ suffix on ticks$ is a naming convention for observables. It has no effect on behavior.
The Observable Contract
An observable can call next any number of times, including zero. After that it can call error or complete once, and only one of the two. After error or complete, the observable emits nothing more and RxJS runs the teardown automatically.
Common Errors
- Expecting work without a subscription. An
HttpClientcall with no subscriber sends no request. - Forgetting teardown. A producer that never ends, such as an interval or an event listener, keeps running and keeps references alive until someone unsubscribes. Later chapters cover the async pipe and
takeUntilDestroyed, which handle this for you. - Assuming subscribers share one producer. Two subscriptions to
ticks$create two separate intervals.
Exercise
If you call ticks$.subscribe(console.log) twice, one second apart, how many intervals are running, and do both subscribers print the same number at the same moment?
Show answer
Two intervals run, one per subscription, because each subscribe call runs the producer function again. Each subscriber has its own count, and the second subscriber starts one second later. When the first subscriber prints 1, the second prints 0 at about the same time.
Exercise
Change the producer so it calls subscriber.complete() after emitting 2, without using unsubscribe. What prints, and does the interval get cleared?
Show answer
Inside the interval callback, add a check: if count is greater than 2 after emitting, call subscriber.complete(). The output is 0, 1, 2, then "done". RxJS runs the returned teardown automatically on completion, so clearInterval is called.