Process Rx events at fixed or minimum intervals

后端 未结 5 1621
花落未央
花落未央 2020-12-17 00:15

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

5条回答
  •  隐瞒了意图╮
    2020-12-17 00:38

    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.

提交回复
热议问题