During a code review of an Angular code base I noticed the following code snippet:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ngOnInit() { | |
this.paramsSub$ = this.route.params.subscribe(params => { | |
this.apiSub$ = dataService.getData(param).subscribe(obj => { | |
this.obj = obj; | |
}); | |
}); | |
} |
What’s wrong with this code?
We are subscribing inside a subscription. This makes it almost impossible to know what subscriptions are open at what moment. Good luck closing these subscriptions in the correct way(which you are doing, right?).
A solution is to rewrite this code to use only 1 subscription. Closing this subscription will automatically clean up all inner streams. Let’s apply some RxJS magic to fix this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ngOnInit() { | |
this.sub$ = this.route.params.pipe( | |
switchMap(param => dataService.getData(param)) | |
).subscribe(obj => { | |
this.obj = obj; | |
}); | |
} |