use*_*955 7 rxjs behaviorsubject angular
因为众所周知应该避免在 BehaviorSubject 上使用 getValue() 方法链接 我想知道读取和更新 BehaviorSubject 的最佳方法是什么。
在我的例子中,我有一个 BehaviorSubject 存储一个对象数组,当我单击一个按钮时,我应该将另一个对象推送到该数组并将新值发送给所有订阅者。
现在我正在做:
this.myBehaviorSubject.next([
...this.myBehaviorSubject.value,
{ new object }
])
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法?
谢谢!!
命令式没有好坏之分,取决于你如何使用它。
发布
使用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想更新当前值并将其发送给观察者,则很难更直接。
获取当前值
从任何 Observable 获取值的自然方法是订阅它。在大多数情况下, getValue这确实是一个坏主意,因为在大多数情况下, Observables 是链接的,异步使用的。例如,如果您想合并或压缩两个订阅者的值,则方法是:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8394 次 |
| 最近记录: |