Promises vs Observables vs Subjects in Angular
Promises:
Promises are a basic component of JavaScript that allow for the handling of asynchronous operations. A Promise offers a value that may be available now, later, or never.
Single Value: Promises are single value that will either be resolved or rejcted.
Immutable State: A Promise's state cannot be modified once it has been resolved or rejcted.
Error Handling: Promises itself have built-in error handling through .catch() or try...catch blocks.
Observables:
Observables, part of the Reactive Programming model, used to handle asynchronous data streams. They are cancellable and capable of emitting several values at once.
Multiple Values: can emit multiple values asynchronously.
Data Stream: represent a stream of data that can be observed over time.
Operators: support operators like map, filter, and merge for manipulating the emitted values.
Subjects:
A special kind of Observable that acts as both an Observer and an Observable. Subjects allows multicasting to multiple Observers.
Multicasting: Subjects can multicast values to multiple Observers.
Imperative: You can push values into the Observable execution by using subjects.
Comparision:
1. Use Cases:
Promises are ideal for single asynchronous operations like fetching data through HTTP API.
Observables are ideal for handling streams of data, such as user input, WebSocket events, or HTTP responses, where multiple values might be emitted over time.
Subjects are ideal for scenarios where multiple parts of an application need to communicate and react to events in real time.
2. Error Handling:
Promises handle errors through the .catch() method.
Observables use the error callback in the subscribe method to handle errors.
Subjects follow the same error-handling mechanisms as Observables.
3. Cancellation:
Promises cannot be cancelled once initiated.
Observables can be unsubscribed, cancelling the ongoing operation.
Subjects can be unsubscribed just like Observables.
4. Flexibility:
Promises offer limited functionality compared to Observables and Subjects.
Observables provide powerful operators and transformations, making them highly flexible and expressive.
Subjects combine the functionality of Observables and Observers, allowing for both multicast and imperative data emission.