Created
April 6, 2020 20:21
-
-
Save ThinkDigitalSoftware/7cf732e541b09d01dfd80274f8f321db to your computer and use it in GitHub Desktop.
Completer example
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'; | |
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