Rxjs可观察生命周期

编程入门 行业动态 更新时间:2024-10-18 21:16:25
本文介绍了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可观察生命周期

本文发布于:2023-11-27 23:33:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640045.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:生命周期   Rxjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!