Created
July 7, 2020 21:32
-
-
Save ThinkDigitalSoftware/15cd819bcc5688783c0328b79b1a7423 to your computer and use it in GitHub Desktop.
/// Future timeout example
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
/// 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