Last active
July 20, 2020 22:17
-
-
Save rrousselGit/38fce442dd55ebc2490320b5f83407a0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'dart:async'; | |
/// This examples starts nested asynchronous operations | |
/// and cancels _everything_ still pending after 1 second. | |
/// | |
/// Then, each individual operation can perform custom clean-up | |
/// inside their `finally` block. | |
const timeoutDuration = Duration(seconds: 2, milliseconds: 100); | |
void main() async { | |
example() // | |
.timeout(timeoutDuration) | |
.first | |
.then( | |
(_) => print('finished'), | |
onError: (_) => print('timed out'), | |
); | |
} | |
Stream<void> example() async* { | |
var completed = false; | |
try { | |
await delayedPrint('hello').first; | |
print('did print hello'); | |
await Future.delayed(Duration(seconds: 1)); | |
print('did delay'); | |
await delayedPrint('world').first; | |
print('did print world'); | |
completed = true; | |
} finally { | |
completed ? print('completed example()') : print('cancelled example()'); | |
} | |
} | |
Stream<void> delayedPrint(String msg) async* { | |
bool completed = false; | |
try { | |
await Future.delayed(Duration(seconds: 1)); | |
print(msg); | |
completed = true; | |
} finally { | |
completed ? print('completed $msg') : print('cancelled $msg'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment