In an Angular 7 Component, I use the RxJS takeUntil() to properly unsubscribe on observable subscriptions.
this.destroy$.next()
is missing in the method ngOnDestroy
(see sample below)? Will it still unsubscribe properly?this.destroy$.complete()
is missing in the method ngOnDestroy
(see sample below)? Will it still unsubscribe properly?
@Component({
selector: 'app-flights',
templateUrl: './flights.component.html'
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly destroy$ = new Subject();
public flights: FlightModel[];
constructor(private readonly flightService: FlightService) { }
ngOnInit() {
this.flightService.getAll()
.pipe(takeUntil(this.destroy$))
.subscribe(flights => this.flights = flights);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
takeUntil
takes next as emission. If only complete()
called it won't unsubscribetry this out:
const a=new Subject();
interval(1000).pipe(takeUntil(a)).subscribe(console.log);
timer(3000).subscribe(_=>a.complete())
this.destroy$
is still in the memory and won't get garbage collectedPlease also take a look here to avoid memory leak when using takeUntil
.
https://medium.com/angular-in-depth/rxjs-avoiding-takeuntil-leaks-fb5182d047ef
Personally I prefer explicit unsubscribe
upon destroy.
Here's a simpler approach:
private readonly destroy$ = new Subject<boolean>();
...
ngOnDestroy() {
this.destroy$.next(true);
this.destroy$.unsubscribe();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With