# IObservable <double> .Average應該如何工作？

## 更新

public static class ObservableExtensions {
private class ContinuousAverager {
private double _mean;
private long _count;

public ContinuousAverager() {
_mean = 0.0;
_count = 0L;
}

//seems that ought to be the responsibility of the IObservable (?)
double delta = value - _mean;
_mean += (delta/(double)(++_count));
return _mean;
}
}

public static IObservable ContinousAverage(this IObservable source) {
var averager = new ContinuousAverager();

}
}


## 原始問題

var ticks = Observable.FromEvent(MarketDataProvider, "MarketTick");

var bids = ticks
.Where(e => e.EventArgs.Quote.HasBid)
.Select(e => e.EventArgs.Quote.Bid);

var bidsSubscription = bids.Subscribe(
b => Console.WriteLine("Bid: {0}", b)
);

var avgOfBids = bids.Average();
var avgOfBidsSubscription = avgOfBids.Subscribe(
b => Console.WriteLine("Avg Bid: {0}", b)
);


I would get two IObservable objects (bids and avgOfBids); one would basically be a stream of all the market bids from my MarketDataProvider, the other would be a stream of the average of these bids.

Bid    Avg Bid
1      1
2      1.5
1      1.33
2      1.5


It seems that my avgOfBids object isn't doing anything. What am I missing? I think I've probably misunderstood what Average is actually supposed to do. (This also seems to be the case for all of the aggregate-like extension methods on IObservable -- e.g., Max, Count, etc.)

## 最佳答案

bids.Scan(new { sum = .0, count = 0 },
(agg, x) => new { sum = agg.sum + x, count = agg.count + 1 })
.Select(agg => agg.sum/agg.count)