Question

I have two hot observables of integer. I want to combine both of them to a resulting one which always notifies observer with new sum every time a new value come in through either of the observables.

Suppose observable1 goes as follows  ....., 3, 5, 9, 10, 16 -->
observable 2 goes like this .............., 1, 3, 2 --->

I want resulting one to maintain a sum in a way that adds everything to the sum coming through 1 and subtracts everything coming through 2 so in above example resulting one would go like this

..........................................37, 38, 35, 38, 33, 35, 26, 16 --->

I am thinking of doing it the following way

var result = Observable.Merge(observable1.Scan((p, n) => p + n), 
                             .observable2.Scan((p, n) => p - n)))
                             .Scan((p, n) => p + n);

Does anybody know a better way?

Was it helpful?

Solution

Instead of Merge and Scan for the outer observable, use CombineLatest:

var result = Observable
    .CombineLatest(
        obs1.Scan(0, (sum, n) => sum + n).StartWith(0), // running sum of first observable
        obs2.Scan(0, (sum, n) => sum + n).StartWith(0), // running sum of second observable
        (sum1, sum2) => sum2 - sum1); // running difference of the 2 sums
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top