Rxjs可观察生命周期 [英] Rxjs Observable Lifecycle

查看:76
本文介绍了Rxjs可观察生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我曾经使用过rxjs,通常我会在我的组件文件中,通过将所述订阅推送到Subscription数组中来跟踪我的所有订阅:

If I am ever working with rxjs, I normally, in my component file, keep track of all of my subscriptions by pushing said subscriptions into a Subscription array:

private subcriptions: Subscription[];

this.subscriptions.push(this.myObservableOne.subscribe(...));
this.subscriptions.push(this.myObservableTwo.subscribe(...));

public ngOnDestroy(): void {
    this.subscriptions.forEach(s => s.unsubscribe());
}

现在,我遇到了一些我认为很有趣的事情.如果我需要从服务订阅Observable:

Now, I am running into something that I thought was interesting. If I instead need to subscribe to an Observable from a service:

this.myService.myObservable.subscribe(...)

谁拥有订阅?我的组件将拥有它,还是服务将拥有它?换句话说,我的服务是否需要实现ngOnDestroy才能取消订阅该Observable?

Who owns the subscription? Will my component own it, or will the service own it? In other words, will my service need to implement ngOnDestroy to unsubscribe from that Observable?

我想这样做:this.subscriptions.push(this.myService.myObservable.subscribe(...));可能有用,但我不确定.

I feel like doing: this.subscriptions.push(this.myService.myObservable.subscribe(...)); might work but I am not entirely sure.

推荐答案

Observable 上调用.subscribe(...)会返回 Subscription .

如果您不将此预订分配给变量(或者将其推送到预订数组),则将丢失对该预订的引用,因此您无法取消订阅该预订,这可能导致内存泄漏

If you don't assign this subscription to a variable (or in your case push it to an array of subscriptions), you will lose reference to this subscription, hence you can't unsubscribe from it, which can cause memory leaks.

因此,您假设将其推送到订阅数组中:

So your assumption of pushing it into array of subscriptions:

this.subscriptions.push(this.myService.myObservable.subscribe(...));

并取消订阅组件的 ngOnDestroy 是正确的.

and unsubscribing in ngOnDestroy of your component is correct.

这篇关于Rxjs可观察生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆