Maxouille
Maxouille

Reputation: 2911

Flutter multiple async methods for parrallel execution

I'm still struggeling with the async/await pattern so I'm here to ask you some precisions.

I saw this page explaining the async/await pattern pretty well. I'm posting here the example that bother me :

import 'dart:async';

Future<String> firstAsync() async {
  await Future<String>.delayed(const Duration(seconds: 2));
  return "First!";
}

Future<String> secondAsync() async {
  await Future<String>.delayed(const Duration(seconds: 2));
  return "Second!";
}

Future<String> thirdAsync() async {
  await Future<String>.delayed(const Duration(seconds: 2));
  return "Third!";
}

void main() async {
  var f = await firstAsync();
  print(f);
  var s = await secondAsync();
  print(s);
  var t = await thirdAsync();
  print(t);
  print('done');
}

In this example, each async method is called one after another, so the execution time for the main function is 6 seconds (3 x 2 seconds). However, I don't understand what's the point of asynchronous function if they are executed one after another.

Are async functions not supposed to execute in the background ? Is it not the point of multiple async functions to fastens the process with parrallel execution ?

I think I'm missing something about asynchronous functions and async/await pattern in flutter so if you could explain me that, it would be very appreciated.

Best

Upvotes: 66

Views: 44481

Answers (9)

ndelanou
ndelanou

Reputation: 921

With the latest versions of Dart, you can use Records to get typed results from parallel async tasks

final (f, s, t) = (firstAsync(), secondAsync(), thirdAsync()).wait;

Upvotes: 4

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.

Resource: https://api.flutter.dev/flutter/dart-async/Future/wait.html

Upvotes: 121

Shun Min Chang
Shun Min Chang

Reputation: 896

Try this resolve.

final List<Future<dynamic>> featureList = <Future<dynamic>>[];
for (final Partner partner in partnerList) {
  featureList.add(repository.fetchAvatar(partner.uid));
}
await Future.wait<dynamic>(featureList);

Upvotes: 3

Afzal
Afzal

Reputation: 419

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 it

void 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.

Upvotes: 21

Shayan khan
Shayan khan

Reputation: 321

you can always use them in a single future

final results = await Future.wait([
  firstAsync();
  secondAsync();
  thirdAsync();
]);

results will be an array of you return type. in this case array of strings.

cheers.

Upvotes: 8

xaethos
xaethos

Reputation: 638

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.

Upvotes: 32

sourav pandit
sourav pandit

Reputation: 9115

If want parallel execution you should switch to multi thread concept called Isolates mix this with async/await concepts . You can also check this website for more

https://buildflutter.com/flutter-threading-isolates-future-async-and-await/

Upvotes: 1

youssef ali
youssef ali

Reputation: 426

i think you miss understood how flutter works first flutter is not multi threaded.....! second if it isn't multi threaded how can it executes parallel tasks, which doesnt happen....! here is some links that will help you understand more https://webdev.dartlang.org/articles/performance/event-loop https://www.dartlang.org/tutorials/language/futures

flutter doesn't put futures on another thread but what happens that they are added to a queue the links that i added are for event loop and how future works. hope you get it , feel free to ask me :)

Upvotes: -2

Tristan Pct
Tristan Pct

Reputation: 614

Using async / await like that is useful when you need a resource before executing the next task.

In your example you don't do really useful things, but imagine you call firstAsync, that gives you a stored authorization token in your phone, then you call secondAsync giving this token get asynchronously and execute an HTTP request and then checking the result of this request.
In this case you don't block the UI thread (user can interact with your app) and other tasks (get token, HTTP request...) are done in background.

Upvotes: -1

Related Questions