Flutter multiple async methods for parrallel execution
Waiting on multiple Futures to complete using Future.wait()If the order of execution of the functions is not important, you can use Future.wait().
The functions get triggered in quick succession; when all of them complete with a value, Future.wait() returns a new Future. This Future completes with a list containing the values produced by each function.
Future .wait([firstAsync(), secondAsync(), thirdAsyncC()]) .then((List responses) => chooseBestResponse(responses)) .catchError((e) => handleError(e));
or with async/await
try { List responses = await Future.wait([firstAsync(), secondAsync(), thirdAsyncC()]);} catch (e) { handleError(e)}
If any of the invoked functions completes with an error, the Future returned by Future.wait() also completes with an error. Use catchError() to handle the error.
The example is designed to show how you can wait for a long-running process without actually blocking the thread. In practice, if you have several of those that you want to run in parallel (for example: independent network calls), you could optimize things.
Calling await
stops the execution of the method until the future completes, so the call to secondAsync
will not happen until firstAsync
finishes, and so on. If you do this instead:
void main() async { var f = firstAsync(); var s = secondAsync(); var t = thirdAsync(); print(await f); print(await s); print(await t); print('done');}
then all three futures are started right away, and then you wait for them to finish in a specific order.
It is worth highlighting that now f
, s
, and t
have type Future<String>
. You can experiment with different durations for each future, or changing the order of the statements.
If anyone new in this problem use the async
. Dart has a function called FutureGroup
. You can use it to run futures in parallel.
Sample:
final futureGroup = FutureGroup();//instantiate itvoid runAllFutures() { /// add all the futures , this is not the best way u can create an extension method to add all at the same time futureGroup.add(hello()); futureGroup.add(checkLocalAuth()); futureGroup.add(hello1()); futureGroup.add(hello2()); futureGroup.add(hello3()); // call the `.close` of the group to fire all the futures, // once u call `.close` this group cant be used again futureGroup.close(); // await for future group to finish (all futures inside it to finish) await futureGroup.future;}
This futureGroup
has some useful methods which can help you ie. .future
etc.. check the documentation to get more info.
Here's a sample usage Example One using await/async
and Example Two using Future.then
.