52. Observables vs Promises: Key Differences
Both Promises and Observables handle asynchronous operations, but their capabilities and behavior differ significantly.
| Feature | Promise | Observable |
|---|---|---|
| Values | Single value (resolves or rejects once). | Multiple values over time (a stream). |
| Execution | Eager (executes immediately upon creation). | Lazy (executes only when subscribed to). |
| Cancellation | Not cancellable (must wait for resolution/rejection). | Easily cancellable via unsubscribe(). |
| Operators | None built-in. Requires external libraries. | Rich collection of functional operators (map, filter, retry). |
| Use Case | Single, immediate task (e.g., single file read). | Continuous data streams (HTTP polling, events, UI changes). |
1. Promises (Single Value, Eager)
javascript const promise = new Promise((resolve, reject) => { console.log('Promise executes NOW.'); setTimeout(() => resolve('Data received'), 1000); });
promise.then(value => console.log(value)); // If we never call .then(), the promise still executes.
2. Observables (Multiple Values, Lazy)
Observables are cold; they only start emitting values when an Observer subscribes.
typescript import { Observable } from 'rxjs';
const observable = new Observable(observer => { console.log('Observable setup, waiting for subscription...'); let count = 0; const intervalId = setInterval(() => { observer.next(count++); if (count > 3) { observer.complete(); clearInterval(intervalId); } }, 500);
// Cleanup logic (unsubscribe) return () => clearInterval(intervalId); });
// Nothing happens until we subscribe const subscription = observable.subscribe(value => { console.log('Received:', value); });
// We can cancel the stream at any time // setTimeout(() => subscription.unsubscribe(), 1600);
Angular utilizes the stream capability of Observables for its reactive nature.