退订多个可观察角度的最佳策略是什么?为了清楚起见,我在应用程序不大且不需要诸如 ngrx 之类的解决方案的情况下使用这种方法,在这种情况下,这将是过度设计 >。
当前,我使用订阅实例来添加所有订阅,然后在销毁组件时调用unsubscribe方法。但是我也看到了使用 rxjs 中的 takeUntil 的替代方法。
export class MyComponent implements OnInit, OnDestroy {
$firstObservable: Observable<number> = timer(0, 1000);
$secondObservable: Observable<number> = timer(0, 1000);
private _subscriptions = new Subscription();
constructor() { }
ngOnDestroy(): void {
this._subscriptions .unsubscribe();
}
ngOnInit(): void {
this._subscriptions .add(
this.$firstObservable.subscribe(console.log));
this._subscriptions .add(
this.$secondObservable.subscribe(console.log));
}
}
什么是最佳解决方案?
答案 0 :(得分:4)
我非常失望,人们甚至没有提到async
管道。
它非常强大,可以让您既不必担心订阅问题,也可以使用推送检测策略。
要使用它,只需从TS中删除订阅,然后将值分配给变量即可输入。
只看代码的简化和简单性(不知道这是不是一个字,但是有点不在乎)
export class MyComponent {
firstObservable$: Observable<number> = timer(0, 1000);
secondObservable$: Observable<number> = timer(0, 1000);
combination$ = combineLatest(this.firstObservable$, this.secondObservable$)
.pipe(tap(() => console.log()));
}
在您的HTML
中<ng-container *ngIf="combination$ | async">
Observables are being observed.
</ng-container>
(即使它不适合您的问题示例,您已经可以看到它更干净更简单了)
最好的是,您不必再担心内存泄漏。 Angular负责所有订阅,让您只关心代码(这是一个好的框架应该做的事情)。
答案 1 :(得分:3)
我建议您使用takeUntil()
管道运算符:https://www.learnrxjs.io/operators/filtering/takeuntil.html
这样,您创建了一个Subject
,它将在ngOnDestroy
上产生价值,并一次取消订阅多个订阅
unsubscribeSignal: Subject<void> = new Subject();
$firstObservable: Observable<number> = timer(0, 1000);
$secondObservable: Observable<number> = timer(0, 1000);
ngOnInit() {
this.$firstObservable
.pipe(
takeUntil(this.unsubscribeSignal.asObservable()),
)
.subscribe(result => {});
this.$secondObservable
.pipe(
takeUntil(this.unsubscribeSignal.asObservable()),
)
.subscribe(result => {});
}
ngOnDestroy(){
this.unsubscribeSignal.next();
// Don't forget to unsubscribe from subject itself
this.unsubscribeSignal.unsubscribe();
}
答案 2 :(得分:1)
通过存储(cd /proc/net; cat sockstat; nc -l 8888& sleep 1; cat sockstat; kill $!; cat sockstat)|grep TCP
对象并在subscribtion
上调用unsubscribe方法的最简单方法。
ngDestory
答案 3 :(得分:0)
我发现这篇文章清楚地解释了有关退订的所有内容。这非常有帮助。
The Best Way To Unsubscribe RxJS Observables In The Angular Applications!