使用 .NET 反应式扩展定期调度 IEnumerable [英] Scheduling a IEnumerable periodically with .NET reactive extensions
问题描述
比如说我有一个可枚举的
Say for example I have an enumerable
dim e = Enumerable.Range(0, 1024)
我希望能够做到
dim o = e.ToObservable(Timespan.FromSeconds(1))
这样 observable 就会每秒产生一个值直到枚举用完.我想不出一个简单的方法这样做.
So that the observable would generate values every second until the enumerable is exhausted. I can't figure a simple way to do this.
推荐答案
我也在寻找解决方案并阅读了 rx 介绍 让我自己:有一个 Observable.Generate()
重载,我用它来制作我自己的 ToObservable()
扩展方法,以 TimeSpan
作为句点:
I have also looked for the solution and after reading the intro to rx made my self one:
There is an Observable.Generate()
overload which I have used to make my own ToObservable()
extension method, taking TimeSpan
as period:
public static class MyEx {
public static IObservable<T> ToObservable<T>(this IEnumerable<T> enumerable, TimeSpan period)
{
return Observable.Generate(
enumerable.GetEnumerator(),
x => x.MoveNext(),
x => x,
x => x.Current,
x => period);
}
public static IObservable<T> ToObservable<T>(this IEnumerable<T> enumerable, Func<T,TimeSpan> getPeriod)
{
return Observable.Generate(
enumerable.GetEnumerator(),
x => x.MoveNext(),
x => x,
x => x.Current,
x => getPeriod(x.Current));
}
}
已在 LINQPad 中测试.只关心在生成的 observable 之后枚举器实例会发生什么,例如处置.任何更正表示赞赏.
Already tested in LINQPad. Only concerning about what happens with the enumerator instance after the resulting observable is e.g. disposed. Any corrections appreciated.
这篇关于使用 .NET 反应式扩展定期调度 IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!