Michael T
Michael T

Reputation: 719

IObservable.Generate for variable interval

I'm very new to using System.Reactive and wondering if my solution can be improved. I'm needing to subscribe to an endless set of events at intervals determined by the previous event. I have seen other solutions here using IObservable.Generate and came up with the following which works but is it good practice?

IDisposable updateJob = Observable.Generate(
    true,
    _ => true,
    _ => CheckForUpdate(),
    _ => _, 
    _ => NextCheck()).Subscribe();

Where NextCheck() returns a TimeSpan and CheckForUpdate() returns a bool and does the event processing.

Upvotes: 1

Views: 119

Answers (1)

Shlomo
Shlomo

Reputation: 14350

On the one hand, if it works... shrug. On the other hand...

Observable.Generate is supposed to be kind of a like a for loop with optional time-gaps built in. So if you wanted to iterate over integers 1-10, pausing i*100 milliseconds in between each iteration, you would do this:

var forLoop = Observable.Generate(
    1,
    i => i <= 10,
    i => i + 1,
    i => i,
    i => TimeSpan.FromMilliseconds(i * 100)
)

The nice thing about this is that Rx manages the iterator-state for you, and you can see it all. You could also achieve the same effect with something like this:

var opaqueForLoop = Observable.Generate(
    GetFirstValue(),
    _ => CheckIfDone(),
    _ => GetNextValue(),
    i => SaveCurrentValue(i),
    _ => GetNextTimespan()
)

But you would have to implement those methods, and you have a bit of unnecessary spaghetti.

Your code looks more like the latter than the former. It could be necessary, depending on your problem, I really have no idea.

The one thing you could clearly do is replace the iterator type to Unit and the value to Unit.Default. Since you're not using the value at all, may as well use an explicitly useless value to make that clear.

Upvotes: 2

Related Questions