取消订阅订阅的最简单方法Angular
问题描述:
您好,Angular非常新。我有大约4个数据库查询,每个都是Subscriptions(rxjs/Rx)
。所以我知道我需要取消订阅每个订阅以节省内存泄漏。我怎样才能优化呼叫?我的意思是,我不想打电话给每个订阅并逐个取消订阅。我想在一次通话中完成所有取消订阅。对不起,如果它是一个愚蠢的问题。任何想法的家伙?在此先感谢取消订阅订阅的最简单方法Angular
答
subscriptions = Subscription[];
someMethod() {
this.subscriptions.push(http.get(...).map(...).subscribe(...));
}
ngOnDestory
this.subscriptions.forEach(s => s.unsubscribe());
}
当observable完成时,取消订阅是多余的。取消订阅仅适用于继续发射事件而未完成的观测值。
如果您只想接收单个事件(或其他数量有限的事件),则可以通过使用像take(x)
这样的操作符,然后在x
事件后完成可观察事件来控制您订阅的可观察事件何时完成。
答
还有做另一种有趣的方式:
@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上解释它,我喜欢这种方式取消订阅!
答
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(...);
}
阅读这可能帮助:https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87 – cartant
您不需要退订http://*.com/questions/35042929/do -you-need-to-unsubscribe-from-angular-2-http-calls-to-prevent-memory-leak –