Angular & Signals (283 Qs)•Part 2: HttpClient, RxJS Observables & Angular Elements (36 - 62)
What is the difference between promise and observable?
Below are the list of differences between promise and observable:
| Observable | Promise |
|---|---|
| Declarative: Computation does not start until subscription, so they can run whenever you need the result | Executes immediately on creation |
| Provides multiple values over time | Provides only one |
| Subscribe method is used for error handling that facilitates centralized and predictable error handling | Push errors to the child promises |
| Provides chaining and subscription to handle complex applications | Uses only .then() clause |
Practical Code Example
typescript
// Promise vs Observable:
// Promise: Eager, single value, not cancellable
const promise = new Promise((resolve) => resolve('Single Value'));
// Observable: Lazy (runs on subscribe), stream of values, cancellable via unsubscribe
import { interval } from 'rxjs';
const stream$ = interval(1000); // 0, 1, 2, 3...
const subscription = stream$.subscribe(val => console.log(val));
subscription.unsubscribe(); // Cancels the timer!