因为众所周知,应避免在BehaviorSubject上使用getValue()方法link 我想知道什么是读取和更新BehaviorSubject的最佳方法。
在我的情况下,我有一个BehaviorSubject存储一个对象数组,当我单击按钮时,我应该将另一个对象推入该数组,并将新值发送给所有订阅者。
现在我正在做
this.myBehaviorSubject.next([
...this.myBehaviorSubject.value,
{ new object }
])
有更好的方法吗?
谢谢!
答案 0 :(得分:1)
冲动到底是好是坏,这取决于您如何使用它。
发布
使用next
方法。这是它的内幕:
// update this._value and call Subject's next method
next(value: T): void {
super.next(this._value = value);
}
// Subject's next method
next(value?: T) {
if (this.closed) {
throw new ObjectUnsubscribedError();
}
if (!this.isStopped) {
const { observers } = this;
const len = observers.length;
const copy = observers.slice();
for (let i = 0; i < len; i++) {
copy[i].next(value);
}
}
}
如果要更新当前值并将其发送给观察者,将很难变得更加直接。
获取当前值
从任何Observable获取值的自然方法是订阅它。 在大多数情况下, getValue
确实不是一个好主意,因为在大多数情况下,可观察对象是链式的,是异步使用的。例如,如果要合并或压缩两个订户的值,则方法是:
zip(Subject_1, myBehaviorSubject).subscribe( val=> console.log(val));
现在,在某些情况下,您只需要同步访问当前值,而无需链接运算符。在这种情况下,请使用getValue
。在引擎盖下:
getValue(): T {
if (this.hasError) {
throw this.thrownError;
} else if (this.closed) {
throw new ObjectUnsubscribedError();
} else {
return this._value;
}
}