{"id":2823,"date":"2023-08-10T16:13:26","date_gmt":"2023-08-10T14:13:26","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=2823"},"modified":"2023-08-10T16:41:13","modified_gmt":"2023-08-10T14:41:13","slug":"new-feauture-takeuntildestroy-angular-v16","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2023\/08\/10\/new-feauture-takeuntildestroy-angular-v16\/","title":{"rendered":"takeUntilDestroy &#038; DestroyRef &#8211; Angular v16"},"content":{"rendered":"\n<p>When subscribing to observables (especially in our components) we have to unsubscribe on destroy to prevent any memory leaks in our application.<\/p>\n\n\n\n<p>There are several options to accomplish this. Now Angular v.16 offers us another (and better) alternative.<\/p>\n\n\n\n<p>Previous methods of unsubscribing from subscriptions added a lot of boilerplate to our classes, which reduced readability. For example, consider the following subscription that needs to be safely handled:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export class Component implements OnInit {\n  data;\n\n  ngOnInit(): void {\n    this.service.getData().subscribe(\n\t    response =&gt; this.data = response.\n    )\n  }\n}<\/code><\/pre>\n\n\n\n<p>We could use&nbsp;<code>takeUntil<\/code>&nbsp;operator with additional&nbsp;<code>subject<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export class Component implements OnInit, OnDestroy {\n  data;\n  destroyed = new Subject()\n\n  ngOnInit(): void {\n    this.service.getData()\n      .pipe(\n        takeUntil(this.destroyed),\n      )\n      .subscribe(\n        response =&gt; this.data = response\n      )\n  }\n\n  ngOnDestroy(): void {\n    this.destroyed.next();\n    this.destroyed.complete();\n  }\n}<\/code><\/pre>\n\n\n\n<p>But as long as we are calling the&nbsp;<code>subscribe<\/code>&nbsp;in the component\u2019s class we will end up with many boilerplate code.<\/p>\n\n\n\n<h4><span class=\"has-inline-color has-vivid-red-color\">Injectable OnDestroy<\/span><\/h4>\n\n\n\n<p>Angular 16 introduced a flexible&nbsp;<code>ngOnDestroy<\/code>, which makes the&nbsp;<code>OnDestroy<\/code>&nbsp;hook injectable.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>destroyRef = inject(DestroyRef);<\/code><\/pre>\n\n\n\n<p>This allows us to inject it into our components instead of using it as a method. As a result, we can modify our&nbsp;<code>takeUntil<\/code>example to something like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export class Component implements OnInit {\n  destroyRef = inject(DestroyRef);\n\n  ngOnInit(): void {\n    const destroyed = new Subject();\n\n    this.destroyRef.onDestroy(() =&gt; {\n      destroyed.next();\n      destroyed.complete();\n    });\n\n    this.service.getData()\n      .pipe(takeUntil(destroyed))\n      .subscribe(response =&gt; this.data = response)\n  }\n}<\/code><\/pre>\n\n\n\n<p><em>This basically means that we don&#8217;t need to implement the&nbsp;<code>ngOnDestroy<\/code>&nbsp;method in our component. All the &#8220;additional&#8221; code can be wrapped within a pipe-able operator, which is what happened<\/em>.<\/p>\n\n\n\n<h4>Special case<\/h4>\n\n\n\n<p>In some cases, we may want to react to the destroy event of another component. For example, consider a scenario where a parent component has a subscription that needs to remain active as long as the child component is on the screen. In this case, we can inject&nbsp;<code>DestroyRef<\/code>&nbsp;in the child component:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export class Child {\n  destroyRef = inject(DestroyRef);\n}<\/code><\/pre>\n\n\n\n<p>We can use the new takeUntilDestroyed operator in the parent component to close the subscription by passing the reference to the&nbsp;<code>DestroyRef<\/code>&nbsp;of the child component. Here is an example implementation for the parent component:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export class Parent {\n  @ViewChild(Child) child: Child;\n\n  ngOnInit(): void {\n     interval(1000)\n       .pipe(takeUntilDestroyed(this.child.destroyRef))\n       .subscribe((count) =&gt; console.log(count));\n  }\n}<\/code><\/pre>\n\n\n\n<p>The count will be logged to the console as long as the&nbsp;<code>Child<\/code>&nbsp;component exists. Upon its destruction, the subscription in the&nbsp;<code>Parent<\/code>&nbsp;will be stopped.<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4><span class=\"has-inline-color has-vivid-red-color\">takeUntilDestroy<\/span><\/h4>\n\n\n\n<p>A new operator which comes into play in Angular 16 \u2014 the&nbsp;<code>takeUntilDestroy<\/code>. This pipe-able operator functions similarly to the example above with&nbsp;<code>takeUntil(this.destroyed)<\/code>, but with almost zero additional code required!<\/p>\n\n\n\n<p>We Just have to add it to the pipe without passing anything, and it will automatically pick up the right&nbsp;<code>OnDestroy<\/code>&nbsp;for the current context \u2014 using injectable OnDestroy.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { takeUntilDestroyed } from '@angular\/core\/rxjs-interop';\n\nexport class Component implements OnInit{\n  data;\n\n  constructor(private service: DataService) {\n    this.service.getData()\n      .pipe(takeUntilDestroyed())\n      .subscribe(response =&gt; this.data = response)\n  }\n}<\/code><\/pre>\n\n\n\n<p>That is all!<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h5>References:<\/h5>\n\n\n\n<p><a href=\"https:\/\/indepth.dev\/posts\/1518\/takeuntildestroy-in-angular-v16\">https:\/\/indepth.dev\/posts\/1518\/takeuntildestroy-in-angular-v16<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>When subscribing to observables (especially in our components) we have to unsubscribe on destroy to prevent any memory leaks in our application. There are several options to accomplish this. Now Angular v.16 offers us another (and better) alternative. Previous methods of unsubscribing from subscriptions added a lot of boilerplate to our classes, which reduced readability. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1965,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[37],"tags":[725,727,726,723,724],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/2823"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=2823"}],"version-history":[{"count":2,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/2823\/revisions"}],"predecessor-version":[{"id":2825,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/2823\/revisions\/2825"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/1965"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=2823"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=2823"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=2823"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}