Skip to content

Instantly share code, notes, and snippets.

@mrverdant13
Last active February 7, 2021 06:32
Show Gist options
  • Save mrverdant13/862be4c1fb446bbb36357a0615bba3b1 to your computer and use it in GitHub Desktop.
Save mrverdant13/862be4c1fb446bbb36357a0615bba3b1 to your computer and use it in GitHub Desktop.
Async call to same object method in parallel
// Dartpad: https://dartpad.dartlang.org/862be4c1fb446bbb36357a0615bba3b1
class AsyncClass {
int value = 0;
int numberOfCalls = 0;
Future<String> getAsyncValue(Duration duration) async {
final callerNumber = ++numberOfCalls;
await Future.delayed(duration);
value++;
final message = 'The $callerNumber° caller finished in the $value° place (took $duration)';
print(message);
return message;
}
}
void main() async {
final asyncObject = AsyncClass();
final results = await Future.wait([
asyncObject.getAsyncValue(const Duration(milliseconds: 2000)),
asyncObject.getAsyncValue(const Duration(milliseconds: 1000)),
asyncObject.getAsyncValue(const Duration(milliseconds: 500)),
asyncObject.getAsyncValue(const Duration(milliseconds: 5000)),
asyncObject.getAsyncValue(const Duration(milliseconds: 200)),
asyncObject.getAsyncValue(const Duration(milliseconds: 3000)),
]);
print('============================================================');
print(results.join('\n'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment