Solving Nested Subscribe Problem in Angular with switchMap
During a code review, I noticed that my Angular code had nested subscribes.
Before (Nested Subscribes example)
this.accountService.getList().subscribe(list => {
this.accountService.getDetails(list).subscribe(details => {
this.details = details;
});
});The reviewer suggested refactoring with switchMap to flatten the observable chain.
This can lead to unreadable code and potential bugs because each subscribe creates a new subscription chain.
I refactored the code using RxJS switchMap, which allows chaining observables in a cleaner way without nesting
Get Suyoung Lee’s stories in your inbox
Join Medium for free to get updates from this writer.
Test Code (Fails)
it('should fetch details', () => {
component.ngOnInit();
// The inner subscribe may not have completed yet
expect(component.details).toBeDefined(); // ❌ This test may fail intermittently
});Issue: Nested subscribes make it hard to control asynchronous flow in tests.
After (Using SwitchMap)
this.accountService.getList().pipe(
switchMap(list => this.accountService.getDetails(list)),
tap(details => this.details = details)
).subscribe();Test Code (Fixed)
it('should fetch details', fakeAsync(() => {
spyOn(accountService, 'getList').and.returnValue(of(['list1']));
spyOn(accountService, 'getDetails').and.returnValue(of(['detail1']));
component.ngOnInit();
tick(); // simulate async passage of time
expect(component.details).toEqual(['detail1']); // ✅ Works reliably
}));Key Takeaways
- Avoid nested subscribes to keep code clean and maintainable
switchMapis useful when the next observable depends on the previous one- Always aim to flatten observable chains for better readability and error handling






