Skip to content

Instantly share code, notes, and snippets.

@ThinkDigitalSoftware
Created April 6, 2020 20:21
Show Gist options
  • Save ThinkDigitalSoftware/7cf732e541b09d01dfd80274f8f321db to your computer and use it in GitHub Desktop.
Save ThinkDigitalSoftware/7cf732e541b09d01dfd80274f8f321db to your computer and use it in GitHub Desktop.
Completer example
import 'dart:async';
final Completer<int> halfwayPointCompleter = Completer();
void main() async {
print('getting started');
calculateSomeNumbers(10).then((result) => print(result)); // async
int halfwayPoint = await halfwayPointCompleter.future;
print(halfwayPoint);
// this will print before the above function completes because it's waiting for the //halfwayPointCompleter to complete, which completes halfway through
}
//function is useless, but it's just an example.
Future<int> calculateSomeNumbers(int max) async {
for (int i = 0; i < max; i++) {
await Future.delayed(Duration(milliseconds: 500));
if (i == max ~/ 2) {
// ~/ is division with rounding. It returns an int.
halfwayPointCompleter
.complete(i); // this makes the future return at this point.
}
}
return max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment