Skip to content

Instantly share code, notes, and snippets.

@rrousselGit
Last active July 20, 2020 22:17
Show Gist options
  • Save rrousselGit/38fce442dd55ebc2490320b5f83407a0 to your computer and use it in GitHub Desktop.
Save rrousselGit/38fce442dd55ebc2490320b5f83407a0 to your computer and use it in GitHub Desktop.
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