Search code examples
system.reactiveenumerable

Scheduling a IEnumerable periodically with .NET reactive extensions


Say for example I have an enumerable

dim e = Enumerable.Range(0, 1024)

I'd like to be able to do

dim o = e.ToObservable(Timespan.FromSeconds(1))

So that the observable would generate values every second until the enumerable is exhausted. I can't figure a simple way to do this.


Solution

  • 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));
        }
    }
    

    Already tested in LINQPad. Only concerning about what happens with the enumerator instance after the resulting observable is e.g. disposed. Any corrections appreciated.