【问题标题】:How to correlate start/end events from an infinite stream?如何关联来自无限流的开始/结束事件?
【发布时间】:2017-10-25 12:45:58
【问题描述】:

我有一个来自 rabbitMQ 的事件流,看起来像
Event: {id, type, timestamp}
这些值是:
id: 一些唯一的字符串
type: (a)rrive/(d)epart

我想生成一个新的事件流,其中我将每个 ID 的到达事件与离开事件(连续)匹配。可以出现相同id的事件 例如,给定一个事件流:

id | type | time  
1  |  a   | 0  
1  |  d   | 1   
2  |  a   | 2  
3  |  a   | 3  
3  |  d   | 4  
1  |  a   | 5  
2  |  d   | 6
1  |  d   | 7  

我会生成一个Correlated:{id, duration} 类型的新流: 其中duration 是两个相关事件的时间戳差异

id | duration  
{1, 1}  
{3, 1}  
{2, 4}
{1, 1}

我已经能够按 id 对传入流进行分组,但无法找到任何有关将事件与另一个事件关联的文档。我正在使用 RxJS

【问题讨论】:

  • 所以length 真的是duration?即到达时间和出发时间之间的差异?
  • 是的,我已经编辑了问题以澄清这一点。
  • 如果给定 id 有多个到达和离开,您应该通过在示例数据中包含它来明确这一点。
  • 抱歉,我已经更新了。
  • 我考虑按 id 对流进行分组,然后键入并使用 bufferdeparture 流,每个 id 都充当关闭通知器。不确定这是否是正确的方向?

标签: rxjs reactive-programming


【解决方案1】:

假设到达先于出发,在groupBy之后,您可以使用pairwise合并连续事件,filter仅考虑出发,map计算持续时间,如下所示:

const source = Rx.Observable.of(
  { id: 1, type: "a", time: 0 },
  { id: 1, type: "d", time: 1 },
  { id: 2, type: "a", time: 2 },
  { id: 3, type: "a", time: 3 },
  { id: 3, type: "d", time: 4 },
  { id: 1, type: "a", time: 5 },
  { id: 2, type: "d", time: 6 },
  { id: 1, type: "d", time: 7 },
  Rx.Scheduler.async
);

const grouped = source
  .groupBy(event => event.id)
  .mergeMap(group => group
    .pairwise()
    .filter(([, last]) => last.type === "d")
    .map(([prev, last]) => ({
      id: last.id,
      duration: last.time - prev.time
    }))
  );

grouped.subscribe(value => console.log(value));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

【讨论】:

  • 到达会先于出发,但是每个 ID 不会只有一个到达/离开。也就是说,我想将每次到达与该 ID 的下一次出发相关联。我会试一试,看看它会带我去哪里
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2021-10-07
相关资源
最近更新 更多