1.
Advanced RxJS Operators
2. Subjects and their types
3. Error handling in Observables
4. Manual subscription management
1. Advanced RxJS Operators in Angular
These operators help you manipulate streams in complex ways.
switchMap
Switches to a new inner Observable, cancelling the previous one.
import { switchMap } from 'rxjs/operators';
[Link](
debounceTime(300),
distinctUntilChanged(),
switchMap(term => [Link](`/api/search?query=${term}`))
).subscribe(results => {
[Link] = results;
});
mergeMap
Allows concurrent subscriptions, useful when you want all inner Observables to complete.
[Link]('/api/items').pipe(
mergeMap(items => [Link](item => [Link](`/api/details/${[Link]}`)))
).subscribe(details => {
// Handle details for all items
});
concatMap
Queues up inner Observables and executes them sequentially.
[Link]$.pipe(
concatMap(action => [Link]('/api/endpoint', action))
).subscribe(response => {
// Each request sent one after another
});
2. Subjects in Angular
A Subject is both an Observable and Observer. It can multicast values to multiple subscribers.
Subject: Basic multicast.
BehaviorSubject: Holds current value, emits it immediately to new subscribers.
ReplaySubject: Emits a specified number of last values to new subscribers.
AsyncSubject: Emits only the last value when completed.
Example with BehaviorSubject
import { BehaviorSubject } from 'rxjs';
export class UserService {
private userSubject = new BehaviorSubject<User | null>(null);
user$ = [Link]();
setUser(user: User) {
[Link](user);
In components:
[Link]$.subscribe(user => {
[Link]('Current user:', user);
});
3. Error Handling
Use catchError to handle errors inside a stream:
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
[Link]('/api/data').pipe(
catchError(err => {
[Link]('Error occurred', err);
return of([]); // Return fallback observable
})
).subscribe(data => {
[Link] = data;
});
4. Manual Subscription Management
When you subscribe manually (without async pipe), remember to unsubscribe to avoid memory
leaks:
import { Subscription } from 'rxjs';
export class MyComponent implements OnDestroy {
private subscription!: Subscription;
ngOnInit() {
[Link] = [Link]('/api/data').subscribe(data => {
[Link] = data;
});
ngOnDestroy() {
[Link]();
Or use the takeUntil operator with a Subject to manage unsubscription cleanly:
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
export class MyComponent implements OnDestroy {
private destroy$ = new Subject<void>();
ngOnInit() {
[Link]('/api/data').pipe(
takeUntil([Link]$)
).subscribe(data => [Link] = data);
ngOnDestroy() {
[Link]$.next();
[Link]$.complete();
Would you want me to generate a full example Angular app showing all these concepts working
together? Or do you want me to explain any operator or concept in more detail?