[英]ForkJoin observable does not unsubscribe when ngOnDestroy
因此,我的應用程序有一個彈出窗口,它具有可觀察到的forkjoin,如果用戶選擇了很多項目,則可能需要很長時間才能運行。 如果用戶在此過程中關閉了窗口,則該應用程序將處於靜止狀態,直到forkjoin完成執行,並且在我的主應用程序中沒有任何工作。 我確實通過使用訂閱取消了forkjoin的訂閱,但是它一直運行到完成為止。 這是我的代碼:
subscriptions: Subscription[] = [];
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscriptions.forEach(s => s.unsubscribe());
}
//get all my items
getItems() {
//set item list to blank
this.itemList = [];
let observables = [];
this.loadItems = true;
//get sections that user selected
this.subscriptions.push(
this.organizationService.GetSelectedSections(this.sectionID, this.culture)
.subscribe(
(selectedSections: GetSelectedSections[]) => {
this.selectedSectionsAll = selectedSections;
//push all selected sections in observables
for (let section in selectedSections) {
observables.push(this.organizationService.GetItemsBySection( selectedSections[section].sectionItemID, this.culture));
}
// get all items in sections to display
if (observables.length != 0) {
this.subscriptions.push(
Observable.forkJoin(observables)
.subscribe(
(result: any) => {
this.itemList = result;
},
(error: any) => {
this.errorMessage = error
this.loadItems = false;
},
() => {
this.loadItems = false;
}
)
);
}
},
(error: any) => {
this.errorMessage = error
},
() => {
}
)
);
}
隨着時間的推移,我了解到正確清理可觀察對象只是一種好習慣。 通常,在我的ngDestroy中,我有:
ngOnDestroy() {
this.updateService.clearUpdate(); //this is where I call the next() method
//on the observable to clear it
this.subscription.unsubscribe(); //I call this directly on the Subscription object
//To clear obviously unsubscribe
this.alive = false; //I use this in the subscribed method in my component
//as a boolean for the rxjs takeWhile() method...
}
我典型的發布/訂閱之一
this.updateService.getUpdate()
.takeWhile(() => this.alive)
.subscribe(message => {...impl...}
我的消息傳遞結構始終在組件類的外部,並且非常簡單
public message = new Subject<any>();
constructor(private zone: NgZone) {
}
sendUpdate(message) {
this.zone.run(() => {
this.message.next(message);
});
}
getUpdate(): Observable<any> {
this.zone.run(() => {
this.message.asObservable();
});
return this.message.asObservable();
}
clearUpdate() {
this.zone.run(() => {
this.message.next();
});
}
我讓事情盡可能簡單。 我還使用了angular的zone()來確保無論何種類型的用戶界面都可以更新。 希望這可以幫助..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.