【发布时间】:2020-08-05 02:55:43
【问题描述】:
在我的应用程序中,我有一些代表当地货币的对象,还有一些代表货币汇率的对象。
我的问题是,如果我的本地货币对象订阅了货币对象上的单个主题以提醒汇率变化(但货币对象实际上并没有保存订阅),然后单个货币实例定义了所有主题这些订阅设置为 null,如果我没有对 50,000 个货币对象中的每一个调用取消订阅,所有这些“订阅”会消失吗?
对于一个具体的(简化的)示例,如下:
import { Subject } from 'rxjs'
interface MyChangeEvent {
oldValue : number;
newValue : number;
}
export class Currency {
rateSubject : Subject<MyChangeEvent>;
private _rate : number;
private _name : string;
constructor(name : string, rate : number) {
this.rateSubject = new Subject();
this._rate= rate;
this._name = name;
}
get rate() : number {
return this._rate;
}
set rate(v : number) {
let oldrate = this.rate;
this._rate = v;
let ce : MyChangeEvent
ce = {} as MyChangeEvent;
ce.newValue = v;
ce.oldValue = oldrate;
this.rateSubject.next(ce);
}
}
export class Money {
private _rate : number = 1;
private _localCurr : number = 0;
get dollarValue() {
return this._localCurr * this._rate;
}
constructor(localCurr : number, curr : Currency) {
this._localCurr = localCurr;
this._rate = curr.rate;
curr.rateSubject.subscribe((change)=>{
this._rate = change.newValue;
})
}
}
const test = function() {
let c = new Currency("USD", 1);
let m = new Money(500, c);
c.rate = .5;
c=null;
}
所以我的问题是,假设我的应用程序中有 50,000 个货币对象,然后我在此处的最后一行设置 c=null。我为所有这些货币对象设置的 50,000 个侦听器是否会持续存在于内存中的某个位置,当货币对象超出范围时,它们是否都被垃圾回收了?
【问题讨论】:
-
我猜
this.rateSubject = new Subject();的 JS 对象仍然保留,因为它包含对您传递给subscribe的回调的引用,这些回调在仍然在某处引用的所有货币对象的范围内跨度> -
我不确定我是否遵循。您是说货币对象保留对订阅的引用,即使货币对象本身不保存订阅?如果不是,我不理解为什么货币中的 rateSubject 不会是 GCd。只要没有活动对象引用它,它维护对回调的引用似乎还不够。基于对安德烈答案的投票达成的共识似乎不同意。但是,你有 77K 的代表,所以 - 你有多自信?
标签: typescript rxjs