Don't forget to unsubscribe
If we start working with Rxjs, we need to be aware to unsubscribe add a certain point.
In an angular application we can do this on different ways:
- async pipe
- takeUntil
- take
- ...
We prefer to use the async pipe in our code. But this is not always possible, so we create a lot of boilerplate code. To avoid this, you can use this library.
yarn add @reibo/ngx-destroy
npm i @reibo/ngx-destroy
- you need to add the
@DestroyClass
to the class, that needs to be destroyed - Add
@Destroy
to your field or function that needs to be destroyed.
##Examples See the stackblitz example: (https://stackblitz.com/edit/ngx-destroy)
import {Component} from '@angular/core';
import {interval} from 'rxjs';
import {map} from 'rxjs/operators';
import {Destroy, DestroyClass} from '@reibo/ngx-destroy'
@DestroyClass
@Component({
selector: 'app-destroy',
templateUrl: './destroy.component.html',
styleUrls: ['./destroy.component.css']
})
export class DestroyComponent {
@Destroy
stream$ = interval(1000).pipe(
map(() => `property ${new Date()}`),
);
@Destroy
getStreamTest() {
return interval(1000).pipe(
map(() => `function ${new Date()}`),
);
}
constructor() {
this.stream$.subscribe();
this.getStreamTest().subscribe(console.log);
}
}
import {Component, OnDestroy} from '@angular/core';
import {interval} from 'rxjs';
import {map} from 'rxjs/operators';
import {Destroy, DestroyClass} from '@reibo/ngx-destroy'
@DestroyClass
@Component({
selector: 'app-destroy',
templateUrl: './destroy.component.html',
styleUrls: ['./destroy.component.css']
})
export class DestroyComponent implements OnDestroy {
@Destroy
stream$ = interval(1000).pipe(
map(() => `property ${new Date()}`),
);
@Destroy
getStreamTest() {
return interval(1000).pipe(
map(() => `function ${new Date()}`),
);
}
constructor() {
this.stream$.subscribe();
this.getStreamTest().subscribe(console.log);
}
ngOnDestroy() {
console.log('destroy')
}
}