Skip to content

Instantly share code, notes, and snippets.

@passsy
Created October 11, 2021 11:58
Show Gist options
  • Save passsy/ee620ed62bad8f6cbecd3997fc867f5e to your computer and use it in GitHub Desktop.
Save passsy/ee620ed62bad8f6cbecd3997fc867f5e to your computer and use it in GitHub Desktop.
Dart CLI, progress indication while awaiting Future
import 'dart:async';
void main() async {
// start future
final future = doHardWork();
// continously post progress
final sub = showProgress().listen((_) {});
// wait for completion
await future;
// stop progress
await sub.cancel();
print("done");
}
Future<void> doHardWork() async {
await Future.delayed(Duration(seconds: 5));
print("Hard work completed");
}
Stream<void> showProgress() {
final start = DateTime.now();
StreamController<void> controller = StreamController();
bool cancelled = false;
controller.onCancel = () {
cancelled = true;
};
() async {
while (true) {
await Future.delayed(Duration(seconds: 1));
if (cancelled) {
return;
}
print("Waiting since ${DateTime.now().difference(start).inSeconds}s");
}
}();
return controller.stream;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment