How to speed up the dynamic time interval in Reactive Extension

I have a scenario where the timer interval changes to every tick event. As below:

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

If I need to implement Timers in Rx for the same. I can use the timer function. But how can I manipulate the Event Interval, as shown in the code above. The current implementation of the timer interval is as follows:

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); 
0
source share
1 answer

You can use Generateto process data generation if it is non-async generation. If your method will use async, although you can flip your own method 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));

    });
  });
}

:

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

Source: https://habr.com/ru/post/1609696/


All Articles