ā All posts
RxJS / Cancel Request with Subscription
Posted On 03.12.2022
In RxJS, a Subscription◹ is an object that represents an execution of an Observable◹. It has the most important method, the unsubscribe()
, mainly used to cancel the execution.
For example, we usually make API calls like this:
this.apiService.post(`/upload`).subscribe(response => {
// upload complete
})
This works fine if our API call run to complete. But what happens if the user cancels the operation in the middle of the API call? For example, the user decided to close the upload dialog.
We can handle such case like this:
startUpload() {
this.upload$ = this.apiService.post(`/upload`);
this.upload$.subscribe(response => {
// upload complete
});
}
cancelUpload() {
if (this.upload$) {
this.upload$.unsubscribe();
}
}