如何在Reactive Extension中推动动态时间间隔

时间:2015-08-19 18:43:25

标签: c# timer system.reactive reactive-programming

我有一个场景,每个tick事件的定时器间隔都会发生变化。如下面的代码所示:

    Timer tmrObj = new Timer();
    tmrObj.Interval = TimeSpan.FromSeconds(11);
    tmrObj.Tick += TimerTickHandler;

   public void TimerTickHandler(EventArg arg)
   {
     tmrObj.pause();

     var response = MakeSomeServiceCall();
     tmr.Interval = response.Interval;

     tmrObj.resume();
   }

如果我需要在Rx中实现同样的计时器。我可以实现使用Timer功能。但是如何在事件勾号上操作Interval,如上面的代码所示。当前的定时器间隔实现如下:

var serviceCall = Observable.FromAsync<DataResponse>(MakeServiceCall);
var timerCall = Observable.Timer(TimeSpan.FromSeconds(100));

var response = from timer in timerCall
               from reponse in serviceCall.TakeUntil(timerCall)
               .Select(result => result); 

1 个答案:

答案 0 :(得分:1)

如果是非异步生成,您可以使用Generate来处理数据生成。如果您的方法将使用异步,但您可以使用自己的GenerateAsync方法:

public static IObservable<TOut> GenerateAsync<TResult, TOut>(
    Func<Task<TResult>> initialState,
    Func<TResult, bool> condition,
    Func<TResult, Task<TResult>> iterate,
    Func<TResult, TimeSpan> timeSelector,
    Func<TResult, TOut> resultSelector,
    IScheduler scheduler = null) 
{
  var s = scheduler ?? Scheduler.Default;

  return Observable.Create<TOut>(async obs => {

    //You have to do your initial time delay here.
    var init = await initialState();
    return s.Schedule(init, timeSelector(init), async (state, recurse) => 
    {
      //Check if we are done
      if (!condition(state))
      {
        obs.OnCompleted();
        return;
      }

      //Process the result
      obs.OnNext(resultSelector(state));

      //Initiate the next request
      state = await iterate(state);

      //Recursively schedule again
      recurse(state, timeSelector(state));

    });
  });
}

请参阅original answer

您可以像这样使用它:

var timeStream = ObservableStatic.GenerateAsync(
  () => MakeServiceCall(),
  _ => true,
  _ => MakeServiceCall(),
  result => result.Interval,
  _ => _);