我从约瑟夫·阿尔巴哈里那里得到一个可观察的东西:
IObservable<int> GetHeartBeat()
{
return Observable.Create<int>((observer, cancelToken) => this.Start(observer, cancelToken));
}
async Task Start(IObserver<int> observer, CancellationToken cancelToken)
{
int beat = 0;
var random = new Random();
while (beat < 10)
{
await Task.Delay(random.Next(500) + 700, cancelToken);
observer.OnNext(beat);
beat++;
}
}
然后我运行这个:
var observable = this.GetHeartBeat()
.TimeInterval()
.Buffer(3, 1)
.Select(l => l.Average(x => 60 / x.Interval.TotalSeconds));
observable
.Select(i => string.Format("{0}, ", i))
.Concat(observable.Count().Select(i => string.Format("{0}", i)))
.Subscribe(i => System.Diagnostics.Debug.WriteLine(i));
observable.Wait();
我希望看到这个:
71.9889864709428, 1
72.9592264002639, 2
67.6743699542054, 3
等。
但我看到这个:
71.9889864709428,
72.9592264002639,
67.6743699542054,
我现在能对错到什么程度?
我认为你需要这个:
var observable = this.GetHeartBeat()
.TimeInterval()
.Buffer(3, 1)
.Select((l, i) => string.Format("{0}, {1}", l.Average(x => 60 / x.Interval.TotalSeconds), i))
.Subscribe(i => System.Diagnostics.Debug.WriteLine(i));
使用
Rx 获取运行总计的标准方法是使用 Scan
运算符。