← Back to Angular, page 1

angular-0016 · Easy fresher

What is an Observable, and how does it differ from a Promise? Why do you need to unsubscribe?

A Promise delivers one value, starts immediately, and cannot be cancelled. An Observable can deliver many values over time, is lazy (it starts on subscribe), can be cancelled by unsubscribing, and has operators to transform the stream. Long-lived Observables must be unsubscribed to avoid memory leaks.

Full answer

Both represent work that finishes later, such as an API call. The differences matter in practice.

A Promise:

  • gives exactly one result or one error;
  • is eager. The work starts when the Promise is created;
  • cannot be cancelled;
  • is consumed with then or await.

An Observable (from RxJS, which Angular uses for HTTP, router events, and forms):

  • can give zero, one, or many values, then complete or error;
  • is lazy. Nothing happens until subscribe();
  • each subscriber normally gets its own execution (cold);
  • can be cancelled, because subscribe() returns a Subscription with unsubscribe();
  • has many operators such as map, filter, debounceTime, and switchMap.

An everyday picture: a Promise is a single exam result slip. An Observable is a live cricket score feed. It keeps sending updates until it ends or you stop listening.

Why unsubscribe? A stream such as interval(1000) or a form's valueChanges never completes by itself. If a component is destroyed while still subscribed, the callback keeps running and holds the component in memory (a leak). HTTP observables complete after one response, so they need no manual cleanup. Safe options: the async pipe, takeUntilDestroyed(), or take(1) and first() for one value.

You can convert between them: firstValueFrom(obs$) and lastValueFrom(obs$) give a Promise, and from(promise) gives an Observable.

typescript
import { Observable, firstValueFrom, interval, take } from 'rxjs';

// A Promise starts immediately.
const promise = new Promise<number>((resolve) => {
  console.log('promise runs now');
  resolve(1);
});

// An Observable does nothing until subscribe().
const numbers$ = new Observable<number>((subscriber) => {
  console.log('observable started');
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
  subscriber.complete();
});
console.log('observable not started');

numbers$.subscribe({
  next: (n) => console.log('value', n),
  complete: () => console.log('done'),
});

// A never-ending stream must be stopped.
const ticks: number[] = [];
const sub = interval(20).subscribe((n) => ticks.push(n));
setTimeout(() => {
  sub.unsubscribe();
  console.log('stopped after', ticks.length, 'ticks');
}, 50);

console.log('promise value', await promise);
console.log('first value', await firstValueFrom(interval(5).pipe(take(1))));

Tested with RxJS 7 and Node 22.18 or newer (`node main.ts`, with a `type: module` package.json). The output is the same on every run. Output: `promise runs now`, `observable not started`, `observable started`, `value 1`, `value 2`, `value 3`, `done`, `promise value 1`, `first value 0`, and finally `stopped after 2 ticks`.

Key points

  • Promise: one value, eager, no cancel. Observable: many values, lazy, cancellable.
  • Nothing runs until `subscribe()`; each subscription usually runs the source again.
  • Unsubscribe from streams that do not complete. HTTP completes by itself.
  • `firstValueFrom` and `from` convert between the two.

Common mistakes

  • Saying Observables are always asynchronous. `of(1, 2, 3)` emits synchronously.
  • Subscribing in a component and never cleaning up an `interval` or `valueChanges` subscription.
  • Using `toPromise()`, which was deprecated in RxJS 7 and removed in RxJS 8. Use `firstValueFrom` or `lastValueFrom`.

Follow-ups

  • What does cold versus hot mean?
  • When would you prefer `firstValueFrom` over subscribing?
  • How does the async pipe prevent leaks?

Tips

  • Use the table of differences: values, laziness, cancellation, operators. It is a clear structure.
  • Say that cancellation is the biggest practical advantage, for example cancelling a search request.
  • Mention `takeUntilDestroyed`, because it is the modern answer to cleanup.

Evaluation rubric

  • States lazy versus eager and one versus many values.
  • Can explain why unsubscribing matters.
  • Knows how to convert and clean up.