Last active
February 7, 2021 06:32
-
-
Save mrverdant13/862be4c1fb446bbb36357a0615bba3b1 to your computer and use it in GitHub Desktop.
Async call to same object method in parallel
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
// 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