Unsubscribing / deleting component cancels my pending request to BE - RxJS

Viewed 31

Last few weeks I have been dealing with memory leaks in my angular app. I have been told that each subscription should have an unsubscribe() call somewhere to prevent any corresponding memory leaks. Thus, I have been adding the following code through my project:

this.testSubscription?.unsubscribe();
this.testSubscription = {observable}.subscribe();

However, I have found out, that in case my component gets destroyed and there is an ongoing backend request it gets automatically canceled, and thus the unexpected result is shown to the user.

Why I am using such a concept?

  • I have a list of items where I am able to delete them. The deletion could potentially take some time and thus I have implemented an optimistic response, sending BE request and deleting the inner component from the list.

Do you think that having a subscription variable is in this case unnecessary and could be removed or do you suggest any other approach to this problem that won't introduce any new memory leaks?

Thanks for your help!

1 Answers

The easiest way to circumvent this is to move your logic into a service. This way, you can trigger your data fetch from the service and when a component x or y destroys itself, the service request carries on and the data could be retrieved from the service itself.

ng generate service xxx will generate you a service.

Injecting a service is as easy as: private service: ServiceName into your component constructor.

Then you could have a method in your service that fetches data with a get request. calling it on the app.component.ts and then retrieving this data from a navbar or other comp.

Good luck!

Related