angularrxjs

Using `takeUntilDestroyed()` outside injection context


I see all examples (such as https://stackoverflow.com/a/76264910/2770274) that uses takeUntilDestroyed outside injection context to use injected DestroyRef like the following:

export class Component implements OnInit {
  destroyRef = inject(DestroyRef);
 
  ngOnInit() {
    this.service.getData()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe();
  }
}

I think it would be a little neater and need less imports to just call the function in the constructor and pass the resulting OperatorFunction where needed:

export class Component implements OnInit {
  takeUntilDestroyed = takeUntilDestroyed();
 
  ngOnInit() {
    this.service.getData()
      .pipe(this.takeUntilDestroyed)
      .subscribe();
  }
}

Looking at the implementation of the function (https://github.com/angular/angular/blob/main/packages/core/rxjs-interop/src/take_until_destroyed.ts) I see no problems with this approach, am I missing something?


Solution

  • Seems to work fine, I do not see any problems implementing it like this. We get the benefit of not passing in destroyRef and getting the auto unsubscription on destroy, best to try it out always.

    Basically by initalizing the MonoTypeOperatorFunction, the destroyRef is scoped to the component reference since it is a function, something like a closure. The function returned can be used inside the pipe in any function without worrying about injection context.

    Nice find!

    import { Component, signal } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import { interval } from 'rxjs';
    import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
    
    @Component({
      selector: 'app-child',
      standalone: true,
      template: `
      child
      `,
    })
    export class Child {
      takeUntilDestroyed = takeUntilDestroyed();
    
      ngOnInit() {
        interval(1000).pipe(this.takeUntilDestroyed).subscribe(console.log);
      }
    }
    
    @Component({
      selector: 'app-root',
      imports: [Child],
      standalone: true,
      template: `
        @if(show()) {
          <app-child/>
        }
        <button (click)="clickEvent()">toggle</button>
      `,
    })
    export class App {
      show = signal(true);
    
      clickEvent() {
        this.show.update((val: any) => !val);
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo