In the process of tidying up a class where I need to execute some code once a condition becomes true (which needs to be checked at a given interval - GPIO input on a Raspberry Pi), inspired by (and based on) the Timer::callAfterDelay
method I wrote this:
struct TimerExtensions
{
struct LambdaConditionalInvoker : private Timer
{
LambdaConditionalInvoker (std::function<bool ()> c, std::function<void ()> f, int interval)
: function (f), condition (c)
{
startTimer (interval);
}
void timerCallback () override
{
if (condition ())
{
auto f = function;
delete this;
f ();
}
}
std::function<void ()> function;
std::function<bool ()> condition;
JUCE_DECLARE_NON_COPYABLE (LambdaConditionalInvoker)
};
static void callOnCondition (std::function<bool ()> c, std::function<void ()> f, int interval = 50)
{
new LambdaConditionalInvoker (c, f, interval);
}
};
I don’t know if its useful enough to warrant going into the Timer class but it might be useful to someone else.
Example usage:
TimerExtensions::callOnCondition ([&]
{
return (checkConditionIsZero() == 0);
},
[this]
{
methodToCall();
});