不,没有。您需要手动订阅和手动取消订阅以避免内存泄漏。
对于简单的订阅,您可能会很想这样做:
@Component({
selector: 'my-component',
})
export class myComponent implements OnInit, OnDestroy {
public myObservable$: Observable<string>;
private myObservableSub: Subscription;
ngOnInit() {
this.myObservableSub = this
.myObservable$
.subscribe(_ => {
// do something
});
}
ngOnDestroy() {
this.myObservableSub();
}
}
但是如果你有很多订阅呢?
您是否应该这样做:
@Component({
selector: 'my-component',
})
export class myComponent implements OnInit, OnDestroy {
public myObservable1$: Observable<string>;
private myObservableSub1: Subscription;
public myObservable2$: Observable<string>;
private myObservableSub2: Subscription;
public myObservable3$: Observable<string>;
private myObservableSub3: Subscription;
ngOnInit() {
this.myObservableSub1 = this
.myObservable1$
.subscribe(_ => {
// do something
});
this.myObservableSub2 = this
.myObservable2$
.subscribe(_ => {
// do something
});
this.myObservableSub3 = this
.myObservable3$
.subscribe(_ => {
// do something
});
}
ngOnDestroy() {
this.myObservableSub1();
this.myObservableSub2();
this.myObservableSub3();
}
}
**答案是不**
更新回复 (16/11/20)
在原始答案中(请参阅此编辑后),我建议使用 take until 但这会强制您创建一个主题并在组件被销毁时触发一个事件。虽然这背后的想法很好,但在我们订阅流的所有组件中放入相当多的样板。
除此之外,我们可以创建一个自定义运算符,我们可以调用 takeUntilDestroyed 并执行以下操作:
@Component({
selector: 'my-component',
})
export class myComponent implements OnInit, OnDestroy {
public myObservable1$: Observable<string>; // define your observable
public myObservable2$: Observable<string>; // define your observable
public myObservable3$: Observable<string>; // define your observable
ngOnInit() {
this
.myObservable1$
.pipe(takeUntilDestroyed(this))
.subscribe(_ => {
// do something
});
this.myObservableSub2 = this
.myObservable2$
.pipe(takeUntilDestroyed(this))
.subscribe(_ => {
// do something
});
this.myObservableSub3 = this
.myObservable3$
.pipe(takeUntilDestroyed(this))
.subscribe(_ => {
// do something
});
}
ngOnDestroy() {}
}
这个自定义操作符的实现可以在这里找到:https://github.com/cloudnc/ngx-sub-form/blob/1115b21a007f72c54b521b3bed7c40051302145a/projects/ngx-sub-form/src/lib/shared/ngx-sub-form-utils.ts#L145-L148
原始回复
您应该执行以下操作:
@Component({
selector: 'my-component',
})
export class myComponent implements OnInit, OnDestroy {
private componentDestroyed$ = new Subject<void>();
public myObservable1$: Observable<string>;
public myObservable2$: Observable<string>;
public myObservable3$: Observable<string>;
ngOnInit() {
this
.myObservable1$
.takeUntil(componentDestroyed$)
.subscribe(_ => {
// do something
});
this
.myObservable2$
.takeUntil(componentDestroyed$)
.subscribe(_ => {
// do something
});
this
.myObservable3$
.takeUntil(componentDestroyed$)
.subscribe(_ => {
// do something
});
}
ngOnDestroy() {
this.componentDestroyed$.next();
this.componentDestroyed$.complete();
}
}
如果您想了解更多相关信息,请查看 Ben Lesh 的一篇精彩文章:https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87
编辑:
感谢@olsn,我编辑了我的答案并添加了next 行,因为确实完整并不会阻止其他流。
我创建了一个小 Plunkr 来演示该行为:https://plnkr.co/edit/dcueDqUgpqgYimxEAGUn?p=preview