<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Balázs Takács on Medium]]></title>
        <description><![CDATA[Stories by Balázs Takács on Medium]]></description>
        <link>https://medium.com/@balzstakcs_53226?source=rss-6b7ac3b57a55------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-ExxRS-BkNJscu_o.</url>
            <title>Stories by Balázs Takács on Medium</title>
            <link>https://medium.com/@balzstakcs_53226?source=rss-6b7ac3b57a55------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 11:30:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@balzstakcs_53226/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Prevent Subscription memory leaks in Angular 16]]></title>
            <link>https://medium.com/@balzstakcs_53226/prevent-subscription-memory-leaks-in-angular-16-9196844b7e92?source=rss-6b7ac3b57a55------2</link>
            <guid isPermaLink="false">https://medium.com/p/9196844b7e92</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Balázs Takács]]></dc:creator>
            <pubDate>Sat, 01 Apr 2023 11:13:37 GMT</pubDate>
            <atom:updated>2023-04-11T08:37:02.784Z</atom:updated>
            <content:encoded><![CDATA[<p>We, Angular developers all know the struggle to make sure we don’t leave Subscriptions open after the corresponding component is destroyed, otherwise we would introduce memory leaks.</p><p>In 2018, I asked the <a href="https://stackoverflow.com/questions/52441328/how-to-unit-test-unsubscribe-function-in-angular">question on StackOverflow</a>: „How to unit test the unsubscribe function in angular”. It generated a lot of discussions and contributors posted tons of interesting solutions.</p><p>A few days ago, I checked what the Angular team plans to ship in version 16. By reading the feature list I saw DestroyRef. It sounded interesting, so I immediately updated my Angular CLI to version 16 and started playing around with it.</p><p>Before discussing the new feature, let&#39;s go through how we usually unsubscribe from Subscriptions in a component.</p><p>Please note that subscribing is our last resort. Use it only for justifiable scenarios. Otherwise, use the async pipe.</p><ol><li><strong>Create a separate class variable for each Subscription</strong></li></ol><pre>private mySubscription1: Subscription;<br>private mySubscription2: Subscription;<br>//...<br>ngOnInit(): void {<br>  this.mySubscription1 = this.store.select(mySelector1)<br>    .subscribe((value: any) =&gt; console.log(value));<br>  this.mySubscription2 = this.store.select(mySelector2)<br>    .subscribe((value: any) =&gt; console.log(value));<br>}<br><br>ngOnDestroy(): void {<br>  this.mySubscription1.unsubscribe();<br>  this.mySubscription2.unsubscribe();<br>}</pre><p>It is not the best solution, because the Subscription variables have to be private, because we don’t want to put them on the public interface, since the template doesn’t use them. Testing private class variables is possible, but hacky, and we all want to keep our work clean.</p><p><strong>2. Create one class variable to act as a parent Subscription</strong></p><pre>private parentSubscription: Subscription[];<br>//...<br>ngOnInit(): void {<br>  this.parentSubscription.add(<br> this.store.select(mySelector1)<br>   .subscribe((value: any) =&gt; console.log(value))<br> );<br>  this.parentSubscription.add(this.store.select(mySelector2)<br>      .subscribe((value: any) =&gt; console.log(value))<br> );<br>}<br><br>ngOnDestroy(): void {<br>  this.parentSubscription.unsubscribe();<br>}</pre><p>Same problem here too. To make our code clean, the parent Subscription has to be private. Also personally, I’m not a big fan of adding child Subscriptions to parent Subscription, because it creates a nested structure, which is hard to read.</p><p><strong>3. Create a Subject that sends a signal to Subscriptions on destroy (takeUntil)</strong></p><pre>private destroy$: Subject&lt;boolean&gt;();<br><br>private mySubscription1: Subscription;<br>private mySubscription2: Subscription;<br>//...<br>ngOnInit(): void {<br>  this.mySubscription1 = this.store.select(mySelector1).pipe(<br>    takeUntil(this.destroy$)<br>  ).subscribe((value: any) =&gt; console.log(value));<br>  this.mySubscription2 = this.store.select(mySelector2).pipe(<br>    takeUntil(this.destroy$)<br>  ).subscribe((value: any) =&gt; console.log(value));<br>}<br><br>ngOnDestroy(): void {<br>  this.destroy$.next(true);<br>  this.destroy$.complete();<br>}</pre><p>Same problem here too. The Subject has to be private.</p><p><strong>4. Auto unsubscribe with decorator</strong></p><pre>function AutoUnsubscribe() {<br>  return function(constructor) {<br>    const originalOnDestroy = constructor.prototype.ngOnDestroy;<br>    constructor.prototype.ngOnDestroy = function() {<br>      for(const prop in this) {<br>        const property = this[prop];<br>        if(typeof property.subscribe === &quot;function&quot;) {<br>          property.unsubscribe();<br>        }<br>      }<br>      originalOnDestroy.apply();<br>    }<br>  }<br>}<br><br>@Component({<br>    ...<br>})<br>@AutoUnsubscribe<br>export class AppComponent implements OnInit {<br>  private mySubscription1: Subscription;<br>  private mySubscription2: Subscription;<br>  //...<br>  ngOnInit(): void {<br>    this.mySubscription1 = this.store.select(mySelector1)<br>      .subscribe((value: any) =&gt; console.log(value));<br>    this.mySubscription2 = this.store.select(mySelector2)<br>      .subscribe((value: any) =&gt; console.log(value));<br>  }<br>}</pre><p>This solution could be a bit slow if we have a lot of variables (code smell) in the component since it checks the class variable signature and calls unsubscribe if possible. Also, we have to store the Subscriptions in class variables. Furthermore, the decorator is still an experimental feature. Most importantly, this solution is also not testable.</p><p>There might be other solutions out there, I’m not aware of. The ideas I listed are the ones I saw used the most.</p><p><strong>DestroyRef</strong></p><p>DestoryRef is a new token the Angular team plans to introduce in version 16. By using the token, we can access onDestroy anywhere within the injection context.</p><p>This made me think, and eventually, I came up with a solution for handling Subscriptions.</p><pre>//util.ts<br>export function destroyable&lt;T&gt;(observable: Observable&lt;T&gt;): Observable&lt;T&gt; {<br>  const subject = new Subject&lt;boolean&gt;();<br>  inject(DestroyRef).onDestroy(() =&gt; {<br>    subject.next(true);<br>    subject.complete();<br>  });<br>  return observable.pipe(takeUntil(subject));<br>}<br><br>//app.component.ts<br>ngOnInit(): void {<br>  destroyable(this.store.select(mySelector1))<br>    .subscribe((value: any) =&gt; console.log(value));<br>  destroyable(this.store.select(mySelector2))<br>    .subscribe((value: any) =&gt; console.log(value));<br>}</pre><p>At the end of the component’s lifecycle, the <em>destroyable </em>unit function takes care of the unsubscribing mechanism.</p><p>It is unit testable too:</p><pre>import * as util from &#39;../util/destroyable&#39;;<br><br>it(&#39;should wrap mySelector1 selection in destroyable&#39;, () =&gt; {<br>  jest.spyOn(util, &#39;destroyable&#39;);<br><br>  fixture.detectChanges();<br>  expect(util.destroyable).toHaveBeenCalledWith(store.select(mySelector1));<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9196844b7e92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>