5

In an Angular 7 Component, I use the RxJS takeUntil() to properly unsubscribe on observable subscriptions.

  • What happens when the this.destroy$.next() is missing in the method ngOnDestroy (see sample below)? Will it still unsubscribe properly?
  • What happens when the this.destroy$.complete() is missing in the method ngOnDestroy (see sample below)? Will it still unsubscribe properly?
  • Is there any way to enforce that pattern with takeUntil() to unsubscribe is properly used (e.g. tslint rule, npm package)?

@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();
    }
}
Horace P. Greeley
  • 682
  • 1
  • 8
  • 17

4 Answers4

2
  1. takeUntil takes next as emission. If only complete() called it won't unsubscribe

try this out:

const a=new Subject();
interval(1000).pipe(takeUntil(a)).subscribe(console.log);
timer(3000).subscribe(_=>a.complete())
  1. this.destroy$ is still in the memory and won't get garbage collected
  2. Not that i am aware of

Please 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.

Marcos Dimitrio
  • 6,100
  • 4
  • 35
  • 59
Fan Cheung
  • 9,632
  • 3
  • 15
  • 36
1

Here's a simpler approach:

private readonly destroy$ = new Subject<boolean>();

...

ngOnDestroy() {
    this.destroy$.next(true);
    this.destroy$.unsubscribe();
}
Paul Story
  • 574
  • 4
  • 10
0

this.destroy$.next() triggers the Subject which triggers the takeUntil operator which completes the flightService.getAll() subscription.

this.destroy$.complete() completes the destroy$ Subject when component is destroyed.

noririco
  • 723
  • 6
  • 15
0

Hi use takeWhile instead of takeUntil.

@Component({
    selector: 'app-flights',
    templateUrl: './flights.component.html'
})
export class FlightsComponent implements OnDestroy, OnInit {
    private readonly destroy$ = new Subject();
    alive = true;
    public flights: FlightModel[];

    constructor(private readonly flightService: FlightService) { }

    ngOnInit() {
        this.flightService.getAll()
            .pipe(takeWhile(() => this.alive))
            .subscribe(flights => this.flights = flights);
    }

    ngOnDestroy() {
        this.alive = false;
        this.destroy$.complete();
    }
}
upinder kumar
  • 719
  • 5
  • 8