【发布时间】:2017-03-08 06:48:30
【问题描述】:
您好,我对 Angular 很陌生。我有大约 4 个数据库查询,每个查询都是 Subscriptions(rxjs/Rx)。所以我知道我需要取消订阅我的每个订阅以节省内存泄漏。如何优化通话?我的意思是,我不想调用每个订阅并一一取消订阅。我想在一个电话中完成所有取消订阅。对不起,如果这是一个愚蠢的问题。有什么想法吗?提前致谢
【问题讨论】:
您好,我对 Angular 很陌生。我有大约 4 个数据库查询,每个查询都是 Subscriptions(rxjs/Rx)。所以我知道我需要取消订阅我的每个订阅以节省内存泄漏。如何优化通话?我的意思是,我不想调用每个订阅并一一取消订阅。我想在一个电话中完成所有取消订阅。对不起,如果这是一个愚蠢的问题。有什么想法吗?提前致谢
【问题讨论】:
subscriptions = Subscription[];
someMethod() {
this.subscriptions.push(http.get(...).map(...).subscribe(...));
}
ngOnDestroy() {
this.subscriptions.forEach(s => s.unsubscribe());
}
当一个 observable 完成时,取消订阅是多余的。取消订阅仅对持续发出事件但未完成的 observables 是必需的。
如果您只想接收单个(或其他有限数量的事件),您可以使用take(x) 之类的运算符来控制您订阅的 observable 何时完成,然后在x 事件之后 observable 将完成。
【讨论】:
export class BaseComponent implements OnDestroy {
protected alive$: Subject<void> = new Subject<void>();
ngOnDestroy(): void {
// console.log("unsubscribing base component");
this.alive$.next();
this.alive$.complete();
}
}
export class EveryComponent extends BaseComponent {
this.AllObs1$.takeUntil(this.alive$).subscribe(...);
}
【讨论】:
还有另一种有趣的方法:
@Component({ ... })
export class SomeComponent implements OnInit, OnDestroy {
private componentDestroyed$ = new Subject();
...
ngOnInit() {
this.yourObs1$.takeUntil(componentDestroyed$).subscribe(...);
this.yourObs2$.takeUntil(componentDestroyed$).subscribe(...);
this.yourObs3$.takeUntil(componentDestroyed$).subscribe(...);
...
this.yourObsX$.takeUntil(componentDestroyed$).subscribe(...);
}
ngOnDestroy() {
this.componentDestroyed$.next();
this.componentDestroyed$.complete();
}
}
在这里,您甚至不需要跟踪订阅,而且您阅读的方式对开发人员更友好(我认为)。
Ben Lesh 在Medium 上解释了它,我喜欢这种退订方式!
【讨论】: