I have a sequence of events that happen every 10-1000 ms. I subscribe to this source of events, but want to handle them at a fixed (or minimum) interval of 500ms. I also wan
This is my attempt:
public static IObservable MinimumInterval(this IObservable source, TimeSpan rate, IScheduler scheduler = null)
{
if (scheduler == null)
scheduler = TaskPoolScheduler.Default;
Func, IDisposable> subscribe = obs => {
var nextTick = scheduler.Now;
var subscriptions = new CompositeDisposable();
Action onNext = value =>
{
var sendTime = Max(nextTick, scheduler.Now);
var disp = new SingleAssignmentDisposable();
disp.Disposable = scheduler.Schedule(sendTime, () =>
{
subscriptions.Remove(disp);
obs.OnNext(value);
});
subscriptions.Add(disp);
nextTick = sendTime + rate;
};
Action onError = err => { subscriptions.Dispose(); obs.OnError(err); };
Action onCompleted = () => { subscriptions.Dispose(); obs.OnCompleted(); };
var listener = Observer.Create(onNext, onError, onCompleted);
subscriptions.Add(source.Subscribe(listener));
return subscriptions;
};
return Observable.Create(subscribe);
}
It keeps track of the earliest the next message can be sent and uses the scheduler to delay events if they occur too soon. The CompositeDisposable ensures scheduled events are cancelled when the listener unsubscribes.
Constructive feedback is welcome.