Skip to content

Instantly share code, notes, and snippets.

@ThinkDigitalSoftware
Created July 7, 2020 21:32
Show Gist options
  • Save ThinkDigitalSoftware/15cd819bcc5688783c0328b79b1a7423 to your computer and use it in GitHub Desktop.
Save ThinkDigitalSoftware/15cd819bcc5688783c0328b79b1a7423 to your computer and use it in GitHub Desktop.
/// Future timeout example
/// Future timeout example
void main() async {
final howLongItTakesToDownloadTheInternet = Duration(days: 365);
final youAreAnImpatientDeveloper = true;
Future downloadTheInternet() =>
Future.delayed(howLongItTakesToDownloadTheInternet);
if (youAreAnImpatientDeveloper) {
// you can use timeout on any future and it'll throw an error if a future doesn't
// complete before you run out of patience.
final resultWithTimeout = await downloadTheInternet()
.timeout(Duration(seconds: 5), onTimeout: () => 'Preloaded Data');
print(
'The download timed out. Here are cached results: $resultWithTimeout');
// this will throw
final resultWithOutTimeout =
await downloadTheInternet().timeout(Duration(seconds: 5));
print(
"We won't get here unless the error is caught, in which cause, you could just use onTimeout");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment