Reputation: 3471
I have a scenario where timer interval changes on every tick event. As shown in below code:
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 achieve using Timer function. But how can I manipulate Interval on event tick as shown in the above code. The current timer interval implementation is as below:
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);
Upvotes: 0
Views: 893
Reputation: 18663
You can use Generate
to handle the data generation if it is a non-async generation. If your method is going to being using async though you can roll your own GenerateAsync
method:
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));
});
});
}
See the original answer
You can use it like so:
var timeStream = ObservableStatic.GenerateAsync(
() => MakeServiceCall(),
_ => true,
_ => MakeServiceCall(),
result => result.Interval,
_ => _);
Upvotes: 1