Last active
June 21, 2021 03:26
-
-
Save guntaka/2c447daec59e7e61c1961527e4b19ede to your computer and use it in GitHub Desktop.
Add delay between calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.Consumer; | |
import java.util.function.Supplier; | |
import io.vavr.Tuple; | |
import io.vavr.Tuple2; | |
import io.vavr.collection.Stream; | |
import io.vavr.control.Option; | |
import io.vavr.control.Try; | |
public class FunctionalRetry { | |
public static <T> Option<T> of(int maxTries, Supplier<T> theWorker, Consumer<Tuple2<Integer, Try<T>>> watch) { | |
return Stream.range(0, maxTries) | |
.map(it -> Tuple.of(it, Try.ofSupplier(theWorker))) | |
.peek(watch) | |
.peek(t -> { if(t._2.isFailure()) try { Thread.sleep(1000); } catch(Exception e) {}; }) | |
.find(result -> result._2.isSuccess()).map(t -> t._2.get()); | |
} | |
public static <T> Option<T> of(int maxTries, Supplier<T> theWorker) { | |
return of(maxTries, theWorker, input -> System.out.println("Iteration:" + input._1 + "> Result:" + input._2)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
import io.vavr.control.Option; | |
public class Main { | |
public static void main(String[] args) { | |
Option<Integer> mayBe = FunctionalRetry.of(10, Main::doSomething); | |
if (mayBe.isDefined()) System.out.println(mayBe.get()); | |
} | |
//Sample test function | |
public static int doSomething() { | |
if (new Random().nextInt(5) != 0) throw new NumberFormatException(); | |
return 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment