Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 74 ยท HTTP and RxJS

RxJS Essentials: Observables

Understand RxJS observables for Angular: lazy streams versus promises, subscribe and unsubscribe, cold versus hot, Subject and BehaviorSubject, with a runnable tiny Observable.

You have already met observables without being introduced. HttpClient returns them, the router publishes events through them, and a form control's valueChanges is one. RxJS is the library behind all of that, and Angular depends on it. You do not need to master it. You need a clear mental model of what an observable is, when it starts and stops, and how to avoid leaking subscriptions. That is what this lesson gives you.

The short version: a Promise is one value that arrives later; an Observable is a recipe for producing zero, one or many values over time, which does nothing until someone subscribes and which can be cancelled. Modern Angular also has signals for state held in components. Observables remain the right tool for events and asynchronous streams: typing in a search box, HTTP calls, WebSockets, timers.

The typescript blocks show real RxJS and Angular code and are read-only, because the site can't run the Angular compiler or install npm packages. The runnable examples are stand-ins: a tiny Observable written in about 40 lines that follows the same rules as RxJS (laziness, a terminal error or complete, teardown on unsubscribe), plus small Subject classes. They are not RxJS itself, and real RxJS has many more features.

Observable versus Promise

Promise Observable
Values exactly one zero, one or many
Starts immediately, when created (the executor runs at once) when subscribed; no subscriber, no work
Cancel not possible unsubscribe() stops the work
Reuse one result shared by everyone who awaits it each subscription normally runs the producer again (cold)
Sync or async always asynchronous either; of(1, 2) emits synchronously
Transform then chains pipe() with operators, see RxJS operators

The laziness difference matters the most. In Angular, this.http.get('/api/users') sends nothing until something subscribes (directly, or through the async pipe, or toSignal). And subscribing twice sends two requests.

Creating and consuming an observable

You create an observable by describing how to produce values. The function you pass receives a subscriber with three methods: next(value), error(err) and complete(). It may return a teardown function that runs when the subscription ends:

TypeScript
import { Observable } from 'rxjs';

const countdown$ = new Observable<number>((subscriber) => {
  let n = 3;
  const id = setInterval(() => {
    subscriber.next(n--);
    if (n < 0) {
      subscriber.complete();
    }
  }, 1000);

  return () => clearInterval(id);   // teardown: runs on unsubscribe, error or complete
});

const subscription = countdown$.subscribe({
  next: (n) => console.log(n),
  error: (err) => console.error(err),
  complete: () => console.log('liftoff'),
});

// later, to stop early:
subscription.unsubscribe();

By convention, variables holding observables end with a $. Most of the time you don't call new Observable yourself; you use creation helpers such as of(1, 2, 3), from(promiseOrArray), interval(1000), timer(500) and fromEvent(button, 'click').

The contract is small and strict:

  • Zero or more next calls, then at most one terminal notification: error or complete. After that, nothing more is delivered.
  • When the subscription ends (the subscriber unsubscribes, or the stream errors or completes), the teardown runs, which is where timers, listeners and requests get released.
  • subscribe returns a Subscription; unsubscribe() on it ends it early. An unsubscribed observer receives no further values.
flowchart LR
  S["subscribe()"] --> P["Producer starts"]
  P --> N["next(value)<br/>zero or more times"]
  N --> N
  N --> E["error(err)"]
  N --> C["complete()"]
  N --> U["unsubscribe()"]
  E --> T["Teardown runs"]
  C --> T
  U --> T

A subscription ends in exactly one of three ways, and the teardown always runs.

The first stand-in builds that contract. Read the code once, then look at the output: the promise starts at creation, the observable only on subscribe, and each subscription runs the producer again.

TypeScript Stand-in: a tiny Observable (lazy, terminal, teardown)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

If you followed the output: step 1 shows the promise's executor ran before anything else, while the observable's producer ran only at subscribe. Step 2 shows each subscriber getting its own run. Step 3 shows the teardown line appearing at unsubscribe(), and silence afterwards. Step 4 shows that after error, the later next and complete calls are ignored.

Unsubscribing in Angular

A subscription to something that never completes (a timer, a DOM event, valueChanges, a router stream) keeps living, along with the component it points to, unless you end it. That is a memory leak, and it also keeps running callbacks on destroyed components. Ways to stay clean, from best to worst:

  1. Don't subscribe by hand. Use the async pipe in the template, or toSignal() in the class; both unsubscribe for you (Signals and RxJS interop).
  2. takeUntilDestroyed() from @angular/core/rxjs-interop: stream$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(...) (the destroyRef argument is optional inside an injection context such as a constructor).
  3. Store the Subscription and unsubscribe in ngOnDestroy: still correct, but tedious and easy to forget.

Streams that complete by themselves, such as an HttpClient call (one response, then done) or of(...), do not need this treatment, although cancelling an HTTP request by unsubscribing is also useful. Don't add cleanup rituals everywhere out of fear; add them where a stream can outlive the component.

Cold and hot

Most observables you create are cold: the producer lives inside the subscribe call, so each subscriber triggers its own execution. HttpClient calls, of, interval and timer are cold. Subscribing twice to an HTTP observable sends two requests.

A hot observable produces values independently of subscribers, and subscribers just listen to whatever happens from the moment they join. A DOM click stream and any Subject are hot. If nobody is listening when a click happens, that click is gone.

flowchart TD
  subgraph Cold
    A1["Subscriber A"] --> P1["Producer run #1"]
    B1["Subscriber B"] --> P2["Producer run #2"]
  end
  subgraph Hot
    A2["Subscriber A"] --> SRC["One shared source"]
    B2["Subscriber B"] --> SRC
  end

Cold: one producer per subscriber. Hot: all subscribers share one source.

You can turn a cold observable into a shared one with the share() operator (or shareReplay, which also remembers values for later subscribers), so that several subscribers cause only one request.

Subject and BehaviorSubject

A Subject is both an observable (you can subscribe) and an observer (you can call next on it). It is hot by nature, and it multicasts each value to all current subscribers. This makes it the bridge between imperative code ("something happened") and streams:

TypeScript
import { BehaviorSubject, Subject } from 'rxjs';

const clicks = new Subject<string>();
clicks.subscribe((id) => console.log('A saw', id));
clicks.next('save');           // A saw save
clicks.subscribe((id) => console.log('B saw', id));
clicks.next('delete');         // A saw delete, B saw delete   (B missed "save")

A BehaviorSubject is a subject that always has a current value. You must give it an initial value, new subscribers receive the latest value immediately, and .value reads it synchronously. That is why it was the standard way to keep shared state in a service:

TypeScript
@Injectable({ providedIn: 'root' })
export class CartCountService {
  private readonly countSubject = new BehaviorSubject<number>(0);
  readonly count$ = this.countSubject.asObservable();   // consumers cannot call next()

  add(): void {
    this.countSubject.next(this.countSubject.value + 1);
  }
}

Always expose asObservable() rather than the subject, so that only the service can push values. There is also ReplaySubject(n), which replays the last n values to late subscribers. Today, for state that lives in a component or service, a signal is usually simpler, because it needs no subscription and has no "initial value" confusion. Keep subjects for event buses and for bridging into streams.

The second stand-in adds Subject, BehaviorSubject and a minimal share(), so you can see cold and hot behavior side by side.

TypeScript Stand-in: Subject, BehaviorSubject and share

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first two blocks are the practical lesson: the cold request ran twice (two different responses), while the shared one ran once and both subscribers got the same response. In the subject block, B joined after save and never saw it; in the behavior block, B was handed the current value 1 the moment it subscribed.

Observables in everyday Angular

You will mostly consume observables that Angular hands you, and subscribe through safe routes:

TypeScript
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-users',
  imports: [AsyncPipe],
  template: `
    @if (users$ | async; as users) {
      <ul>
        @for (user of users; track user.id) {
          <li>{{ user.name }}</li>
        }
      </ul>
    } @else {
      <p>Loading...</p>
    }
  `,
})
export class UsersComponent {
  protected readonly users$ = inject(HttpClient).get<{ id: number; name: string }[]>('/api/users');
}

The async pipe subscribes when the view appears, unsubscribes when it is destroyed, and triggers change detection when a value arrives. The next lessons build on this: operators to transform streams, and HttpClient to talk to servers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you create an observable with new Observable(...) but never call subscribe on it?

    Unlike a Promise's executor, an observable's producer runs only when someone subscribes. No subscriber, no work.
  2. 2. A cold observable has two subscribers. How many times does its producer run?

    Cold observables run the producer for each subscription. An HTTP observable subscribed twice sends two requests, unless you share it.
  3. 3. What is the difference between Subject and BehaviorSubject?

    A plain Subject delivers only values emitted after a subscriber joins, while a BehaviorSubject replays its latest value to every new subscriber and exposes it as .value.
  4. 4. Which is the safest way to avoid a leak when showing an observable's latest value in a template?

    The async pipe and toSignal manage the subscription for you and clean up when the component is destroyed.
  5. 5. After an observable calls error(), what happens to later next() calls?

    An observable ends with exactly one terminal notification, either error or complete, and then runs its teardown. Nothing is delivered afterwards.

Summary

  • An Observable is a lazy recipe for zero, one or many values over time; nothing happens until subscribe, and unsubscribe cancels it.
  • A subscription ends with error, complete or unsubscribe, and the teardown function always runs.
  • Cold observables (HTTP, of, interval) run once per subscriber; hot ones (DOM events, subjects) share one source. share() makes a cold stream shared.
  • Subject multicasts to current subscribers; BehaviorSubject also holds a current value for new subscribers. Expose asObservable(), not the subject.
  • Prefer the async pipe, toSignal or takeUntilDestroyed to manual subscriptions.
  • The RxJS snippets are read-only; the tiny Observable, Subject and share here are stand-ins.

Next: RxJS Operators You Need