Buffer
和Window
向前看,你想要的東西回頭看。 Scan
是最好的起點:
public static IObservable<List<T>> BackBuffer<T>(this IObservable<T> source, TimeSpan ts)
{
return BackBuffer(source, ts, Scheduler.Default);
}
public static IObservable<List<T>> BackBuffer<T>(this IObservable<T> source, TimeSpan ts, IScheduler scheduler)
{
return source
.Timestamp()
.Scan(new List<Timestamped<T>>(), (list, element) => list
.Where(ti => scheduler.Now - ti.Timestamp <= ts)
.Concat(Enumerable.Repeat(element, 1))
.ToList()
)
.Select(list => list.Select(t => t.Value).ToList());
}
一旦你有了BackBuffer
,或類似的東西,那麼剩下變得容易:
source
.BackBuffer(TimeSpan.FromMilliseconds(70))
.Select(list => list.Average())
.Subscribe(average => Console.WriteLine(average));