There are several ways to unsubscribe from observables on Angular components (by using ngOnDestroy). Which option below should be preferred and why (e.g. technical reasons, performance, etc.)?
Option 1: takeUntil
Using RxJS takeUntil to unsubscribe
@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();
}
}
Option 2: .unsubscribe()
Explict call .unsubscribe(), e.g. by using a separate subscription instance
@Component({
selector: "app-flights",
templateUrl: "./flights.component.html"
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly subscriptions = new Subscription();
public flights: FlightModel[];
constructor(private readonly flightService: FlightService) {}
ngOnInit() {
const subscription = this.flightService
.getAll()
.subscribe(flights => (this.flights = flights));
this.subscriptions.add(subscription);
}
ngOnDestroy() {
this.subscriptions.unsubscribe();
}
}
Option 3: takeWhile
Using RxJS takeWhile unsubscribe
TLDR; there is no wrong here. Choose what you see fits your needs and communicates your intent.
Ben Lesh has also written quite a good post about the different ways to unsubscribe https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87
His opinion:
Personally, I choose option 1 as well, which is to use
takeUntil
.However, it is important for you to place the
takeUntil()
operator on the last RxJS operator on the pipe sequence, as explained here.For instance, if we do not place
takeUntil()
as the last operator, the subscriber will remain subscribed to the subsequentswitchMap()
operator:Therefore, the right way of doing so would be this:
Brian Love has written a really good article on the different ways (including
unsubscribe()
, and thetakeUntil()
operator) of unsubscribing to observables. I would recommend you to take a look at it as well.For your example I wouldn't choose any of the 3 options. When you only want to assign a value, then store the Observable and subscribe to it with async pipe.