Remove Redundant Subscriptions in Angular with @jsverse/letify
Shahar Kazaz
Posted on October 30, 2024
In modern web applications, performance and maintainability are key.
✨ Letify is here to help you remove redundant subscriptions in your Angular templates by automatically identifying these duplications and replacing them with @let
variable declarations.
A Quick Reminder: The Async Pipe and Its Pitfall
The async
pipe is a widely used feature in Angular for handling observables and promises in templates. However, it has a drawback: it creates a new subscription each time it's used.
<p>{{ (data$ | async).name }}</p>
<p>{{ (data$ | async).description }}</p>
In this example, data$ | async
is used twice, leading to multiple subscriptions to the same observable. This can degrade performance, especially in large applications.
Before Angular v18.1, solutions to this problem included capturing the value in an ngIf
statement or using third-party libraries like @rx-angular/template with its rxLet
directive.
With the introduction of @let
in Angular v18.1, you can now manage async data more efficiently by creating a single subscription and reusing it throughout your template:
@let data = data$ | async;
<p>{{ data.name }}</p>
<p>{{ data.description }}</p>
But, there's still the challenge of refactoring your existing codebase and keeping those redundant subscriptions away in the future. That's where letify
comes in!
What is @jsverse/letify
?
The @jsverse/letify
CLI tool helps developers automatically detect and optimize redundant async
pipe subscriptions in their templates. It scans your HTML files, identifies duplicate subscriptions, and replaces them with the @let
directive to enhance performance.
Using letify
is straightforward. Once installed, you can run it against your project files to generate a report:
npm i -D @jsverse/letify
npx letify [analyze|fix] 'src/app/**/*.html' ...
Analyze: Scans your templates and highlights opportunities for refactoring.
Fix: Automatically replaces occurrences where possible.
You can even integrate letify
into your CI pipeline or Git hooks to catch these issues before code is committed.
✨Conclusion
Angular's new features continuously enhance app performance and readability. Because of asyncpopularity, duplicated subscriptions are common. letify is your Swiss army knife to easily tackle this issue and optimize your templates.
Join the ️@jsverse Community
I'm excited to see how letify
can enhance your Angular apps! Be sure to check out the @jsverse/letify
repository, give it a star, and follow the jsverse organization
for more updates and tools that will help you build better apps.
Posted on October 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.