Until Destroy
The untilDestroyed
operator is used to unsubscribe from observables when the component is destroyed. It is part of the @ngneat/until-destroy
package.
Installation
To install the @ngneat/until-destroy
package, run the following command in your terminal:
npm install @ngneat/until-destroy
Usage
To use the untilDestroyed
operator, you need to import it from the @ngneat/until-destroy
package and use it in the pipe()
method of the observable, as well as annotate the component with @UntilDestroy()
. For example, the following code uses the untilDestroyed
operator to unsubscribe from the timer
observable when the component is destroyed:
import { Component, OnInit } from '@angular/core';
import { timer } from 'rxjs';
import { untilDestroyed } from '@ngneat/until-destroy';
@UntilDestroy()
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
ngOnInit() {
timer(0, 1000)
.pipe(untilDestroyed(this))
.subscribe(() => {
console.log('Hello World');
});
}
}
If you don't want to unsubscribe from one or more subscriptions, you can use the blacklist option of the @UntilDestroy()
decorator.
@UntilDestroy({ checkProperties: true, blackList: ['subscription1'] })
@Component({})
export class HomeComponent {
// subscription1 will not be unsubscribed upon component destruction
subscription1: Subscription;
// subscription2 will be unsubscribed upon component destruction
subscription2: Subscription;
constructor() {
this.subscription1 = new Subject().subscribe();
this.subscription2 = new Subject().subscribe();
}
}