Observables are a powerful tool in RxJS (Reactive Extensions for JavaScript) that allow handling asynchronous data streams efficiently. They are widely used in Angular for managing data from APIs, user interactions, WebSockets, and events.
Key Features of Observables
Asynchronous Processing – Unlike normal function calls, Observables allow operations that take time (like API requests) to be handled smoothly.
Streams of Data – They can emit multiple values over time, unlike Promises that resolve only once.
Lazy Execution – Observables do not start execution until subscribed.
Multiple Subscribers – A single Observable can have multiple consumers (subscribers).
Operators for Transformation – RxJS provides operators like map(), filter(), merge(), etc., to manipulate data.
Breakdown
observer.next(value): Emits a value to the subscribers.
observer.complete(): Marks the completion of the Observable (no more values).
The subscriber function consumes the emitted values.
Handling HTTP Requests with Observables
Handling HTTP Requests with Observables
Angular’s HttpClient returns Observables by default for API calls.
Observables vs Promises
A Promise resolves once and cannot emit multiple values.
An Observable emits multiple values and can be canceled (unsubscribe()).
Observable Operators (RxJS)
Operator Description
map() Transforms each emitted value
filter() Filters values based on a condition
take(n) Takes only the first n values
debounceTime(ms) Ignores values for a set duration
switchMap() Cancels previous request & switches to the latest one
Unsubscribing from Observables (Memory Management)
Automatically unsubscribes when destroy$ emits a value.
Avoids manual unsubscribe() calls.
✅ Observables are essential in Angular for handling asynchronous data.
✅ They emit multiple values over time and can be transformed using RxJS operators.
✅ Always unsubscribe to prevent memory leaks.
✅ Subjects enable data sharing between components.
Top comments (0)