I want to create a class that can run a method until a condition about the return value is fulfilled.
It should look something like this
methodPoller.poll(pollDurationSec, pollIntervalMillis)
.method(dog.bark())
.until(dog -> dog.bark().equals("Woof"))
.execute();
My method poller look somewhat like this () // following GuiSim answer
public class MethodPoller {
Duration pollDurationSec;
int pollIntervalMillis;
public MethodPoller() {
}
public MethodPoller poll(Duration pollDurationSec, int pollIntervalMillis) {
this.pollDurationSec = pollDurationSec;
this.pollIntervalMillis = pollIntervalMillis;
return this;
}
public <T> MethodPoller method(Supplier<T> supplier) {
return this;
}
public <T> MethodPoller until(Predicate<T> predicate) {
return this;
}
}
But I am having a hard time going opn from here.
How can I implement a retry to a general method until a condition is fulfilled?
Thanks.
Yes, this can easily be done in Java 7 and even cleaner using Java 8.
The parameter to your
method
method should be ajava.util.function.Supplier<T>
and the parameter to youruntil
method should be ajava.util.function.Predicate<T>
.You can then use method references or lambda expressions to create you Poller like so:
As a side note, if you're going to use Java 8, I'd recommend using
java.time.Duration
instead of an integer to represent the poll duration and the interval.I'd also recommend looking into https://github.com/rholder/guava-retrying which is a library that you could perhaps use. If not, it could be a good inspiration for your API as it features a nice fluent API.
EDIT: Following the update to the question, here is a simple implementation. I've left some parts for you to complete as TODOs.
Sample use: