Created
July 11, 2019 09:55
-
-
Save haarts/e7577e927af10c1c0e30a05389599aca to your computer and use it in GitHub Desktop.
Elegant retries
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
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