What is @ngneat/until-destroy?
@ngneat/until-destroy is an Angular utility that helps manage the lifecycle of subscriptions and other resources in Angular components and services. It automatically unsubscribes from observables when the component or service is destroyed, preventing memory leaks and reducing boilerplate code.
What are @ngneat/until-destroy's main functionalities?
Automatic Unsubscription
This feature allows automatic unsubscription from observables when the component is destroyed. The `untilDestroyed` operator is used to bind the observable to the component's lifecycle.
import { Component } from '@angular/core';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { interval } from 'rxjs';
@UntilDestroy()
@Component({
selector: 'app-example',
template: '<p>Example works!</p>'
})
export class ExampleComponent {
constructor() {
interval(1000)
.pipe(untilDestroyed(this))
.subscribe(val => console.log(val));
}
}
Service Support
This feature extends the automatic unsubscription functionality to services. The `untilDestroyed` operator can be used in services to manage subscriptions and other resources.
import { Injectable } from '@angular/core';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { interval } from 'rxjs';
@UntilDestroy()
@Injectable({
providedIn: 'root'
})
export class ExampleService {
constructor() {
interval(1000)
.pipe(untilDestroyed(this))
.subscribe(val => console.log(val));
}
}
Directive Support
This feature allows the use of `untilDestroyed` in directives, providing the same automatic unsubscription functionality as in components and services.
import { Directive, OnDestroy } from '@angular/core';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { interval } from 'rxjs';
@UntilDestroy()
@Directive({
selector: '[appExample]'
})
export class ExampleDirective implements OnDestroy {
constructor() {
interval(1000)
.pipe(untilDestroyed(this))
.subscribe(val => console.log(val));
}
ngOnDestroy() {
// Custom cleanup logic if needed
}
}
Other packages similar to @ngneat/until-destroy
ngx-take-until-destroy
ngx-take-until-destroy is another Angular utility for managing subscriptions. It provides a similar functionality to @ngneat/until-destroy by using a `takeUntilDestroy` operator to handle unsubscriptions. However, @ngneat/until-destroy offers a more modern and streamlined API.
take-until-destroy
take-until-destroy is a lightweight library that helps manage subscriptions in Angular components. It uses a `takeUntil` operator to unsubscribe from observables. While it provides similar functionality, @ngneat/until-destroy offers a more comprehensive and integrated solution.