Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two event streams on a common event property?

Consider the following two event streams. Every event has a timestamp/ts and value property.

Input stream

I want to combine these two streams where the events have the same timestamps, into a resulting stream with an applied transformation of the value. If one stream is missing one timestamp (such as the yellow ts=3 in the example below), that timestamp should be disregarded.

enter image description here

Would like to solve the problem using a reactive programming library such as xstream or rxjs. I'm quite new to the concepts of reactive programming, but if someone has another suggestion I'm all ears. Thanks!

like image 426
hampusohlsson Avatar asked Apr 26 '16 18:04

hampusohlsson


1 Answers

Just use combineLatest and pass only those combinations that have a matching timestamp. The other combinations are mapped to null, which you filter out later.

Here's the solution in xstream:

var streamOut = xs.combine(
  (a, b) => {
    if (a.ts === b.ts) {
      return {ts: a.ts, value: a.value + b.value};
    } else {
      return null;
    }
  },
  streamA, streamB
).filter(x => x !== null);

Check it running in JSBin: https://jsbin.com/saxawatuza/edit?js,console.

like image 129
André Staltz Avatar answered Nov 12 '22 04:11

André Staltz