【问题标题】:RxJS Subject conditional next() update, based on current-new valueRxJS Subject 有条件的 next() 更新,基于 current-new 值
【发布时间】:2020-08-29 19:46:58
【问题描述】:

我有一个在主题中存储一些数据的 Angular 应用程序

dataSubject = new Subject<SomeDataType>();

我有两种不同的方式从服务器更新数据,看起来像

connection1.on('messageReceived', (newData: SomeDataType) => this.dataService.dataSubject.next(newData))
connection2.on('messageReceived', (newData: SomeDataType) => this.dataService.dataSubject.next(newData))

问题是最后到达的新数据不一定是最新的。 每个数据对象都包含一个我想要使用的时间戳。

有没有办法让 Subject 只接受具有 newData.timestamp > currentData.timestamp 的值?类似于条件 next()

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    听起来像是 scan 运算符的一个案例:

    latestData$ = this.dataSubject.pipe(
      // scan will give you the last emitted value and the current value coming through
      // so you can compare them and select which to emit
      scan((last, current) => {
        if (last.timestamp > current.timestamp) {
          return last
        }
        return current;
      }),
      // optional operator to prevent emitting the same value twice 
      distinctUntilChanged()
    );
    

    latestData$ 只会在时间戳大于使用此设置的先前发出的值时发出值。

    【讨论】:

    • 检查current是否定义的原因是什么
    • 第一个值通过,当前将未定义,因为之前没有发射,而且我们没有定义种子参数
    • @bryan60 我认为没有必要这样做。如果种子参数为not provided,它将立即将值作为next 通知发送,而不是调用提供的函数。
    • 似乎根本不需要。奇怪的设计决策,因为扫描经常(通常?)在实践中改变发射的形状,并且如果改变形状似乎是可疑的,那么对种子值的隐藏,硬依赖。我一直假设/期望它反映数组 reduce 的行为
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2019-11-04
    • 1970-01-01
    • 2022-01-04
    • 2012-02-18
    • 2015-04-15
    • 1970-01-01
    相关资源
    最近更新 更多