Skip to content

Instantly share code, notes, and snippets.

@haarts
Created July 11, 2019 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haarts/e7577e927af10c1c0e30a05389599aca to your computer and use it in GitHub Desktop.
Save haarts/e7577e927af10c1c0e30a05389599aca to your computer and use it in GitHub Desktop.
Elegant retries
var fail = true;
int sheep() {
if (fail) {
fail = false;
throw Exception("boom!");
}
return 1;
}
Future<dynamic> retry(Function f, {Duration retryDelay, int numberOfRetries}) {
try {
return Future.value(f.call());
} catch (_) {
if (numberOfRetries > 0) {
return Future.delayed(
retryDelay, () => retry(f, numberOfRetries: numberOfRetries - 1));
} else {
rethrow;
}
}
}
void main() async {
print(await retry(() => sheep(),
retryDelay: Duration(seconds: 1), numberOfRetries: 1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment