读取和更新 BehaviorSubject 值的最佳方式

Best way to read and update a value of a BehaviorSubject

众所周知,应该避免在 BehaviorSubject 上使用 getValue() 方法 我想知道阅读和更新 BehaviorSubject 的最佳方式是什么。

在我的例子中,我有一个 BehaviorSubject 存储对象数组,当我点击一个按钮时,我应该将另一个对象推送到数组并将新值发送给所有订阅者。

现在我在做:

this.myBehaviorSubject.next([
    ...this.myBehaviorSubject.value,
    { new object }
])

有没有更好的方法?

谢谢!!

命令式没有好坏之分,就看你怎么用了。

发布

使用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 确实是一个坏主意,因为,在大多数情况下, 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;
    }
}