Observables & Observers in RxJS
๐ Observables & Observers in RxJS – Complete Angular Guide
๐ Introduction
RxJS (Reactive Extensions for JavaScript) is a powerful library used in Angular for reactive programming. It enables handling asynchronous data streams using Observables, a pattern that allows multiple emissions over time.
In Angular, Observables are commonly used with:
HttpClientfor API calls- Reactive Forms (
FormControl.valueChanges) - Routing events and user interactions
๐ What Are Observables?
An Observable is a data stream that can emit multiple values over time. It follows the Observer pattern, where an Observer subscribes to listen for values, errors, or completion signals from the Observable.
⚙️ Creating Observables in RxJS
๐ป Basic Observable Example
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
observer.next('Hello');
observer.next('RxJS');
observer.complete();
});
observable.subscribe(value => console.log(value));
observer.next(value): Emits a value.observer.complete(): Signals the end of the stream.observer.error(err): Emits an error and stops the stream.
observer.error() in your subscriptions to prevent uncaught exceptions.⚠️ Error Handling Example
const errorObservable = new Observable(observer => {
observer.next('Before error');
observer.error('Something went wrong');
});
errorObservable.subscribe({
next: val => console.log(val),
error: err => console.error('Caught Error:', err),
complete: () => console.log('Completed')
});
๐ Subscribing & Unsubscribing
To receive values from an Observable, you subscribe to it. In Angular components, you must unsubscribe when the component is destroyed to prevent memory leaks.
✅ Subscribing Example
const observable = new Observable(observer => {
observer.next('First Value');
setTimeout(() => observer.next('Second Value'), 2000);
setTimeout(() => observer.complete(), 3000);
});
const subscription = observable.subscribe({
next: value => console.log('Received:', value),
complete: () => console.log('Observable Completed'),
});
๐งน Unsubscribing Example (Angular)
import { Component, OnDestroy } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
@Component({
selector: 'app-example',
template: `Check the console
`
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;
constructor() {
const observable = new Observable(observer => {
setInterval(() => observer.next('Emitted Value'), 1000);
});
this.subscription = observable.subscribe(value => console.log(value));
}
ngOnDestroy() {
this.subscription.unsubscribe();
console.log('Unsubscribed');
}
}
๐ Observables vs Promises
While Promises handle a single asynchronous value, Observables provide greater flexibility and control over asynchronous data streams.
| Feature | Observables | Promises |
|---|---|---|
| Lazy Execution | ✅ Yes | ❌ No |
| Multiple Values | ✅ Yes | ❌ No |
| Cancellation | ✅ Yes (unsubscribe) | ❌ No |
| Operators | ✅ map, filter, debounceTime, switchMap | ❌ Not available |
| Error Handling | ✅ Can recover and continue | ❌ Ends execution |
๐ Promise Example
const promise = new Promise(resolve => {
setTimeout(() => resolve('Promise Resolved'), 2000);
});
promise.then(value => console.log(value));
๐ Observable Example
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
observer.next('Observable Emitted');
setTimeout(() => observer.next('Observable Emitted Again'), 2000);
});
observable.subscribe(value => console.log(value));
✅ Conclusion
- Observables offer more flexibility than Promises.
- They're essential for Angular features like HTTP, forms, and events.
- Always unsubscribe to prevent memory leaks in Angular components.
Tip: Prefer the async pipe in Angular templates to automatically manage subscriptions.
๐ Next Topics: Explore Subject vs BehaviorSubject along with switchMap to master reactive patterns in Angular.
Comments
Post a Comment