【问题标题】:Detect when an observable has emitted the same value twice in a row检测 observable 何时连续两次发出相同的值
【发布时间】:2018-10-12 20:32:29
【问题描述】:

我使用来自this answer的方法对我的websocket连接使用保持活动机制:

Observable.timer(0, 5000)
  .map(i => 'ping')
  .concatMap(val => {
    return Observable.race(
      Observable.of('timeout').delay(3000),
      sendMockPing()
    );
  })

如果发生超时,我需要完全重置 websocket 连接(因为这可能意味着连接断开),但有时单个超时可能只是随机发生(我猜是由于服务器实现不佳?)

我的订阅逻辑目前是这样实现的

).subscribe(result => {
  if (result === 'timeout') {
    // Reconnect to server
  }
}

有什么方法(最好使用 RxJs)以某种方式映射 observable,以便我可以识别它连续两次发出 'timeout' 的情况?

【问题讨论】:

  • 如果您只对忽略两个相似的事件感兴趣,您还可以利用distinctUntilChanged 运算符

标签: node.js websocket rxjs timeout observable


【解决方案1】:

你可以使用scan 操作符来做你想做的事:

source.pipe(
  scan((previous, next) => {
    if ((previous === 'timeout') && (next === 'timeout')) {
      throw new Error('Two consecutive timeouts occurred.');
    }
    return next;
  }, undefined);
);

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 2018-02-03
    • 2023-04-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多