Sta*_*tan 1 observable rxjs angularfire2 angular
遵循此Stack Overflow帖子中描述的最佳实践:Angular RxJS何时应取消订阅订阅,请考虑此Angular组件生命周期钩子:
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();
}
Run Code Online (Sandbox Code Playgroud)
作为authState()和mergeMap()两个返回Observables,我想我应该
takeUntil()从外部Observable authState()或内部Observable 调用其中一个运算符this.todoService.getUserTodos(user.uid).哪个方法是正确的,以确保在组件被销毁后取消订阅所有Observable?
您不需要两个takeUntil运算符.您只需要一个,但行为将根据您删除的行为而有所不同.
如果你只使用第一个takeUntil,如下所示:
this.fireAuth.authState
.takeUntil(this.ngUnsubscribe)
.mergeMap((user) => this.todoService.getUserTodos(user.uid))
.subscribe((todos) => this.userTodoArray = todos);
Run Code Online (Sandbox Code Playgroud)
当this.ngUnsubscribe发出next通知,takeUntil将从订阅this.fireAuth.authState源将完成.如可观察合同中所述,当观察完成时,其订户会收到complete通知并自动取消订阅.
但是,如果一个next通知,从发射this.fireAuth.authState和观测到的返回getUserTodos在mergeMap尚未完成,mergeMap实现将不会从退订getUserTodos观察到.如果getUserTodosobservable稍后发出next通知,则通知将流向subscribe.
如果你只使用第二个takeUntil,如下所示:
this.fireAuth.authState
.mergeMap((user) => this.todoService.getUserTodos(user.uid))
.takeUntil(this.ngUnsubscribe)
.subscribe((todos) => this.userTodoArray = todos);
Run Code Online (Sandbox Code Playgroud)
当this.ngUnsubscribe发出next通知时,takeUntil遗嘱将取消订阅mergeMap,取消订阅this.fireAuth.authState任何返回的getUserTodosobservable.
因此,在this.ngUnsubscribe发出后,没有任何通知会流向subscribe.这可能是您正在寻找的行为,因此您应该删除第一个takeUntil运算符.
| 归档时间: |
|
| 查看次数: |
1452 次 |
| 最近记录: |