Reputation: 23187
I'm facing with an issue related with how to create a dynamic "timer" observable.
Slightly I mean, I need to perform a function and according the value it returns (integer representing the number of seconds) I need to call the same function after these seconds have elapsed. So, I guess I need to re-schedule the observable according this another new value seconds.
I've tried to find something overthere but I',ve not been able to figure out what do I need to do.
Any ideas?
Upvotes: 0
Views: 413
Reputation: 117029
Use Observable.Generate
. Try this example:
void Main()
{
Observable
.Generate(
0, // initialState
x => x < 10, //condition
x => x + 1, //iterate
x => x, //resultSelector
x => TimeSpan.FromSeconds(GetSeconds())) //timeSelector
.Timestamp()
.Subscribe(x => Console.WriteLine($"{x.Value} {x.Timestamp}"));
}
private double _seconds = 2.0;
public double GetSeconds()
{
if (++_seconds > 5.0)
{
_seconds = 2.0;
}
return _seconds;
}
It produces the following output:
0 2017/09/27 12:47:24 +00:00 1 2017/09/27 12:47:28 +00:00 2 2017/09/27 12:47:33 +00:00 3 2017/09/27 12:47:35 +00:00 4 2017/09/27 12:47:38 +00:00 5 2017/09/27 12:47:42 +00:00 6 2017/09/27 12:47:47 +00:00 7 2017/09/27 12:47:49 +00:00 8 2017/09/27 12:47:52 +00:00 9 2017/09/27 12:47:56 +00:00
The first result appears after 3.0
seconds (because of the initial ++seconds
) and the next value after 4.0
seconds as seen by the difference in the timestamp.
It stops after 10 values due to the x => x < 10, //condition
.
Upvotes: 4