Skip to main content

subscribe/unsubscribe in Angular

think that everyone, at least once during the code optimization, realized that they have forgotten to unsubscribe from an observable. This common issue can be very frustrating and time-consuming, especially when you are working on a complex application. Luckily, there is a solution for that.
During the optimization of the project I’m currently working on, I have encountered this issue that could be prevented by using the Async pipe. The built-in Async pipe in Angular 2+ is a great tool to manage observable subscriptions, which is why I have decided to write this article about it.
What is the Async pipe?
The Async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the Async pipe marks the component to be checked for changes. When the component gets destroyed, the Async pipe unsubscribes automatically to avoid potential memory leaks.
Benefits of using Async pipe
  • We can use onPush strategy
  • No need to use or worry about subscribe or unsubscribe
  • No need to use Angular lifecycles
  • Cleaner code
Angular strategies
  • checkAlways
  • onPush
Angular uses default checkAlwaysstrategy. This means that every component is checked when any change is detected, which will reduce the performance.
This issue can be prevented with Async pipe by using onPush strategy. This means we will minimize change detection cycles to check component only when:
  • Input properties change
  • Event emits
  • Observable emits
Using onPush detection strategy is great for performance, so we should be using the Async pipe as much as possible.
How to start using the Async pipe?
The first step is to split our application into multiple components so that every component will have component, html and service file.
With this approach, developers can easily understand the architecture of the Angular application because every component will be the same.
The file example.services.ts is like a container where we specify from where we are fetching the data for our application. The advantage of this is that all the methods that communicate with the backend will be in one place. This way, our code will become much cleaner and easier to maintain.
The next step is to add change detection in example.component.ts manually, as you can see in the picture below:
Then we will just include service in the component and get the methods we need from it. We don’t have to use Init or Destroy lifecycle in our component. We don’t have to create additional properties where we will save data we get; we will just use observables in HTML.
Therefore, we don’t have to worry if we forgot to unsubscribe in some places, and we will be sure we don’t have memory leaks in the application. Everything is done automatically.
While I was doing the optimization of my current project, I found many places where we forgot to unsubscribe, which consumed a lot of time to fix. That could have been avoided by using the Async pipe in the first place.
The last step is to write this expression in HTML so Angular would know that we are using the Async pipe. Every time our component loads, the Async pipe will be triggered, and it will automatically call the method.
Example:
Reload data on some event
You can see from the code above I used combineLatest method from rxjs to combine users observable with behavior subject. This means that every time the event is triggered, we will get the newest data. We can also use this approach if we need to combine a couple of observables into one, which can be seen in the next example.
Here I also used combineLatest from rxjs, but this time to combine observables. This can be useful when you have a component with multiple methods. In order to have cleaner and more readable code, we can combine all observables into one and use only once Async pipe in HTML.
This article is just a brief example of how we can implement the Async pipe to make our applications reactive and easier to maintain.
Thank you for reading.

Comments

Popular posts from this blog

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...