问题
Hi am very new to Angular. I have around 4 database queries and each of them are Subscriptions(rxjs/Rx). So I know I need to unsubscribe each of my subscriptions to save memory leakage. How can I optimise the calling? I mean, I don't want to call each subscription and unsubscribe one by one. I wanna do it all the unsubscribe in one call. Sorry if its a stupid question. Any idea guys? Thanks in advance
回答1:
subscriptions = Subscription[];
someMethod() {
this.subscriptions.push(http.get(...).map(...).subscribe(...));
}
ngOnDestroy() {
this.subscriptions.forEach(s => s.unsubscribe());
}
When an observable completes, unsubscribing is redundant. Unsubscribing is only necessary for observables that continueally emit events without completing.
If you only want to receive a single (or otherwise limited number of events) you can control when the observable you subscribed to completes by using an operator like take(x), then after x events the observable will complete.
回答2:
There's also another interesting way to do that :
@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();
}
}
Here, you don't even need to keep track of a subscription and the way you read is more dev friendly (I think).
Ben Lesh explained it on Medium and I like this way to unsubscribe !
回答3:
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://stackoverflow.com/questions/42664741/easiest-way-to-unsubscribe-subscriptions-angular