2017-03-08 109 views
3

您好,Angular非常新。我有大约4个数据库查询,每个都是Subscriptions(rxjs/Rx)。所以我知道我需要取消订阅每个订阅以节省内存泄漏。我怎样才能优化呼叫?我的意思是,我不想打电话给每个订阅并逐个取消订阅。我想在一次通话中完成所有取消订阅。对不起,如果它是一个愚蠢的问题。任何想法的家伙?在此先感谢取消订阅订阅的最简单方法Angular

+1

阅读这可能帮助:https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87 – cartant

+1

您不需要退订http://stackoverflow.com/questions/35042929/do -you-need-to-unsubscribe-from-angular-2-http-calls-to-prevent-memory-leak –

回答

4
subscriptions = Subscription[]; 

someMethod() { 
    this.subscriptions.push(http.get(...).map(...).subscribe(...)); 
} 

ngOnDestory 
    this.subscriptions.forEach(s => s.unsubscribe()); 
} 

当observable完成时,取消订阅是多余的。取消订阅仅适用于继续发射事件而未完成的观测值。

如果您只想接收单个事件(或其他数量有限的事件),则可以通过使用像take(x)这样的操作符,然后在x事件后完成可观察事件来控制您订阅的可观察事件何时完成。

+1

我正在写关于取消订阅冗余的评论,但你在编辑时速度更快:)。一些很好的阅读有关:http://stackoverflow.com/a/41177163/7447071 – mickdev

+0

Goold链接(像从carcant一个)。 –

+0

@Günter,据我所知,当一个流完成后,它会在拆解中取消订阅,在这种情况下,我们不需要手动取消订阅。但是,我不清楚何时启动http调用,并且用户在调用返回之前从视图导航或者根本不返回。我听说如果发生这种情况,就会造成泄漏,你能否确认或否认? – Thibs

0

还有做另一种有趣的方式:

@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上解释它,我喜欢这种方式取消订阅!

0
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(...); 
}