What is an Observable?
An Observable is a declarative way to handle asynchronous messages in your application. Think of it as a 'stream' of data that can emit multiple values over time. As a Lead Developer, you'll encounter Observables everywhere in Angular: from the HttpClient that fetches your Flutter project data to the Router that tracks URL changes. Unlike a Promise, which executes immediately and returns a single value, an Observable is 'lazy' and doesn't start emitting data until someone subscribes to it.
- The Observable Lifecycle
An Observable follows a specific path: it is created, a consumer subscribes to it, it emits values (or an error), and eventually, it completes.
- Next: A notification that sends a value in the stream.
- Error: A notification that the stream encountered an issue; no more values will be sent.
- Complete: A notification that the stream has finished successfully.
- Creating and Subscribing
To use the data from an Observable, you must use the .subscribe() method. This is common when calling services to populate your UI components.
- Unsubscribing: Preventing Memory Leaks
When a component is destroyed, any active subscriptions might continue to run in the background. For an Architect, managing these 'zombie' subscriptions is vital. Always store your subscription in a variable and call .unsubscribe() in the ngOnDestroy lifecycle hook, or use the async pipe in your HTML templates to let Angular handle it for you.
Observables vs. Promises
| Feature | Observable | Promise |
|---|---|---|
| Values | Multiple (Stream) | Single |
| Execution | Lazy (on subscribe) | Eager (immediate) |
| Cancellation | Supported via unsubscribe() | Not supported natively |
| Operators | Powerful (map, filter, etc.) | Limited (then, catch) |