2017-03-08 106 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(...); 
}