Following the best practices as described in this Stack Overflow post: Angular RxJS When Should I Unsubscribe From Subscription, consider this Angular component lifecycle hook:
private ngUnsubscribe: Subject<void> = new Subject();
ngOnInit() {
this.fireAuth.authState
.takeUntil(this.ngUnsubscribe)
.mergeMap((user) => this.todoService.getUserTodos(user.uid))
.takeUntil(this.ngUnsubscribe)
.subscribe((todos) => this.userTodoArray = todos);
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
As authState()
and mergeMap()
both return Observables, I think I'm supposed to either
- Unsubscribe from both of them (as shown above) or
- Only call one of the
takeUntil()
operators, either from the outer ObservableauthState()
or the inner Observablethis.todoService.getUserTodos(user.uid)
.
Which method is correct to make sure all Observables are unsubscribed after the component is destroyed?