Angular 角度:我应该取消订阅switchMap吗
我有以下组件:Angular 角度:我应该取消订阅switchMap吗,angular,rxjs,Angular,Rxjs,我有以下组件: @Component({...}) export class AppComponent implements OnInit, OnDestroy { destroy$ = new Subject(); update$ = new Subject(); result: Result; constructor(service: Service) { } ngOnInit() { update$.pipe( takeUntil(thi
@Component({...})
export class AppComponent implements OnInit, OnDestroy {
destroy$ = new Subject();
update$ = new Subject();
result: Result;
constructor(service: Service) {
}
ngOnInit() {
update$.pipe(
takeUntil(this.destroy$),
switchMap(() => this.service.get())
).subscribe(result => this.result = result);
this.refresh();
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
refresh() {
this.update$.next();
}
}
这种方法正确吗?或者我应该在switchMap
之后调用takeUntil(this.destroy$)
update$.pipe(
switchMap(() => this.service.get()),
takeUntil(this.destroy$)
).subscribe(result => this.result = result);
或者我应该叫它两次
update$.pipe(
takeUntil(this.destroy$),
switchMap(() => this.service.get()),
takeUntil(this.destroy$)
).subscribe(result => this.result = result);
通常您希望
takeUntil
应该是最后一个操作符。在您的情况下,这是正确的方法:
update$.pipe(
switchMap(() => this.service.get()),
takeUntil(this.destroy$)
).subscribe(result => this.result = result);
最干净的方法是在
switchMap
之后调用takeUntil
update$.pipe(
switchMap(() => this.service.get()),
takeUntil(this.destroy$)
).subscribe(result => this.result = result);
这将防止对订阅的任何排放。如果在之前添加takeUntil
,则switchMap
订阅将发出值,直到project
函数返回的可观察值完成,这可能永远不会完成(取决于您的服务代码)
在
switchMap
之前和之后都不需要调用take,因为switchMap
在其自身被取消订阅时,会从可观察的源(在switchMap
之前的所有内容)取消订阅。它会同时从主题和服务结果中取消订阅吗?是的,它会同时从两者中取消订阅