portfolio / notes / rxjs-fundamentals.mdoc

Understand the stream, then the operator

A visual guide to RxJS fundamentals: Observables versus Promises, how to read a stream diagram, pipe() and subscribe(), and the first three operators: map, filter and tap.

4 min read

  • RxJS
  • Angular
Marble diagram: the values 1, 2 and 3 go through map(n => n * 10) and come out as 10, 20 and 30.

Stop memorizing operator names. Follow what happens to each value instead: once you can read one value through a pipe, every operator is just a rule about what it does to that value.

One result, or a stream of values

A Promise settles once: one fulfillment value or one rejection, at most. new Promise(executor) runs the executor immediately, and its .then() callbacks always run asynchronously. It has no built-in cancellation method.

An Observable delivers zero to many values, and may complete or error. A cold source starts a new execution for each subscription; a hot source can share a producer that is already running. Emissions can be synchronous or asynchronous.

unsubscribe() stops your subscription, not necessarily the source.

PromiseObservable
ValuesOne, or a rejectionZero to many
StartsThe executor runs at once, in new Promise()On subscribe (cold) or already running (hot)
TimingCallbacks always asynchronousSynchronous or asynchronous
CancelNo built-in methodunsubscribe() stops your subscription

Reading the diagram

Time moves from left to right. Each dot is a value; each line is a stream.

source$ABnext(A)next(B)completeearlierlater
Two values, then completion.
  • next(A): a value is emitted.
  • | complete: the stream ends normally.
  • X error: the stream ends with a failure.

No more values arrive after complete or error. These lines are not execution threads: they only show when values happen.

pipe() composes, subscribe() connects

const doubled$ = source$.pipe(map((n) => n * 2));

doubled$.subscribe(console.log);

pipe() composes the operators into a new Observable without subscribing to the chain; a hot source may already be producing values on its own. subscribe() registers the consumer and, on a cold source, starts its execution for that subscription. With Angular's HttpClient, each subscription sends a request. Angular's async pipe can manage the subscription for you.

unsubscribe() ends your side, finalize() cleans up

There is a third way for a subscription to end, and it comes from the other side. unsubscribe() is not a notification of the Observable: nothing is emitted, and neither complete nor error runs. It is something the subscriber does to its subscription: stop listening, and let the source release what it was holding for it.

source$ABnext(A)next(B)unsubscribe()earlierlater
Nothing is emitted at the mark: the subscription stops, and the source may go on unobserved.

That release is the teardown: the function a source returns when it is created. It runs however the subscription ends: complete, error or unsubscribe. finalize() lets you hook into the same moment from a pipe.

const ticks$ = new Observable<number>((subscriber) => {
  const id = setInterval(() => subscriber.next(Date.now()), 1000);
  return () => clearInterval(id); // teardown
});

const sub = ticks$
  .pipe(finalize(() => console.log('cleaned up')))
  .subscribe(render);

sub.unsubscribe(); // the interval stops and 'cleaned up' is logged
How it endsWho ends itObserver callbackTeardown and finalize
completeThe sourcecomplete()Run
errorThe sourceerror(err)Run
unsubscribe()The subscriberNoneRun

map changes the value, filter decides what passes

input$output$map(n => n * 10)102030123
map changes every value.
input$output$filter(n => n >= 20)2030no emission102030
filter drops the values that fail the test.

filter drops emissions; it does not emit true or false.

tap observes without transforming

input$output$tap(n => console.log(n))2030log: 20log: 302030
tap logs each value; the stream carries on unchanged.

Returning a value from tap does not change the emitted value. Use it to observe; avoid mutating objects inside it.

Putting it together

Follow one value and read the whole pipe:

source$
  .pipe(
    map((n) => n * 10),
    filter((n) => n >= 20),
    tap((n) => console.log(n)),
  )
  .subscribe(render);
InputAfter mapOutput
1, 2, 310, 20, 3020, 30

2 becomes 20. It passes the filter. tap logs 20, and the subscriber receives 20.

map transforms, filter selects, tap observes.

Check yourself

Pick an answer to see whether it is right, and why.

How many requests does this code send?
const user$ = this.http.get<User>('/api/user');
user$.subscribe(renderHeader);
user$.subscribe(renderMenu);

HttpClient returns a cold Observable: each subscribe() starts its own execution, and each execution sends a request.

You call pipe() on a cold source but never subscribe(). What runs?

pipe() composes the operators without subscribing to the chain. On a cold source, nothing starts until subscribe().

What does render receive?
of(10, 20, 30).pipe(filter((n) => n >= 20)).subscribe(render);

filter decides what passes: it drops 10 and emits 20 and 30 unchanged. It never emits true or false.

What is logged?
of(5).pipe(tap((n) => n * 2)).subscribe(console.log);

Returning a value from tap does not change the emitted value: tap observes, map transforms.

You call sub.unsubscribe() on a running subscription. What happens?

unsubscribe() is an action on the subscription, not a notification: nothing is emitted, so neither complete nor error runs. The teardown still releases the source's resources, and finalize() runs with it.

A stream has emitted complete (|). What can arrive after it?

Complete and error both end the stream. No more values arrive after either.

Sources: Observable and operators in the RxJS docs, and the HTTP client guide in Angular's docs.

Have a product in mind? Let’s talk.

An idea on a napkin, a process that slows your team down, a product that needs another pair of hands: tell me about it. I read every message and answer with honest questions, not a sales pitch.