Created
October 11, 2021 11:58
-
-
Save passsy/ee620ed62bad8f6cbecd3997fc867f5e to your computer and use it in GitHub Desktop.
Dart CLI, progress indication while awaiting Future
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
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