I’d like to try something every second for five seconds, return false if they are all false, and return true the first time one is true. Imperatively, it’d look like this:
bool TryFiveTimes()
{
for (int i = 0; i < 5; i++)
{
if (Fn())
return true;
System.Threading.Thread.Sleep(1000);
}
return false;
}
I’d like to do this using Rx, but can’t think of a neat way. My current attempt is:
bool TryFiveTimes()
{
return Observable.Interval(TimeSpan.FromSeconds(1))
.Take(5)
.Select(_ => Fn())
.Scan(false, (curr, prev) => curr || prev)
.Last();
}
This will give the correct result, but won’t return early if Fn() returns true before the end.
You could try using
ConcatwithReturnlike this: