By Diego Liascovich
Full-Stack Developer | Angular
π Introduction
RxJS Observables are a core part of Angular β but for many developers, their real power becomes obvious only through actual use cases. Whether you're handling asynchronous data, reacting to UI events, or chaining complex operations, Observables can simplify your code while improving maintainability.
In this post, Iβll walk you through real-world use cases where Observables shine β with code examples you can plug into your own apps.
π§ͺ 1. API Calls and Async Data Flow
A typical and practical use case is managing API requests. Observables allow cancellation, chaining, and transformation.
β Example: Fetch products from an API
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>('/api/products').pipe(
tap(() => console.log('Products fetched')),
catchError((err) => {
console.error(err);
return of([]);
})
);
}
Subscribe in a component:
ngOnInit() {
this.productService.getProducts().subscribe(products => {
this.products = products;
});
}
π 2. Refreshing Data Automatically (Polling)
Need to auto-refresh a table or dashboard every X seconds?
β Example: Poll every 10 seconds
polling$ = timer(0, 10000).pipe(
switchMap(() => this.http.get<Data[]>('/api/status'))
);
ngOnInit() {
this.polling$.subscribe(data => this.statusList = data);
}
π¬ 3. Reactive Form Value Changes
Reacting to changes in user input (like search fields) is extremely powerful with valueChanges
.
β Example: Debounced search
this.searchControl.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(term => this.productService.search(term))
).subscribe(results => {
this.searchResults = results;
});
π¦ 4. State Management with BehaviorSubject
BehaviorSubject
helps store and share state reactively across components.
β Example: Auth token
private tokenSubject = new BehaviorSubject<string | null>(null);
setToken(token: string) {
this.tokenSubject.next(token);
}
getToken$(): Observable<string | null> {
return this.tokenSubject.asObservable();
}
πΈοΈ 5. Combine Streams: Multiple HTTP Calls in Parallel
With forkJoin
, combineLatest
, and zip
, you can run multiple requests together.
β Example: Load user and their orders
forkJoin({
user: this.api.getUser(id),
orders: this.api.getUserOrders(id)
}).subscribe(({ user, orders }) => {
this.user = user;
this.orders = orders;
});
π§ Bonus: Conditional Logic with iif
Want to switch logic based on a condition? Use iif
!
iif(() => this.authService.isLoggedIn(),
this.api.getDashboard(),
of(null)
).subscribe(data => this.dashboard = data);
β Conclusion
Observables are not just for HTTP. Theyβre a powerful reactive abstraction that can help you:
- Handle async flows with clarity
- Compose data from multiple sources
- React to UI and state changes efficiently
- Improve code maintainability
Top comments (0)