0

I want to use Future.wait() to wait for uploading a lot of files to a server and improve the speed of the process. But I wonder if the given Futures run asynchronously on a separate thread?

For example:

I have Future.wait([future1(), future2(), future3()]).

Does it run like this?:

await future1();
await future2();
await future3();

If yes, how can I wait for completing more Isolates?

And can you give me some documentation on this?

Ovidiu Uşvat
  • 701
  • 1
  • 6
  • 29
  • 3
    `Future.wait` doesn't "run" `Future`s. Those asynchronous operations have already started running before `Future.wait` is even invoked. (Dart is an *applicative-order* language: arguments are eagerly evaluated before invoking the function.) Whether those asynchronous operations run in parallel (on separate OS threads, separate Dart isolates, separate processes, whatever) or not depends on the implementations of those operations. Also see https://stackoverflow.com/a/72543144/. – jamesdlin May 25 '23 at 08:20

1 Answers1

0
Future.wait([future1(), future2(), future3()])

Run the 3 futures in parallel. It's better than:

await future1();

await future2();

await future3();

The following example explain the benefits of Future.wait([]):

    Future<String> getValue1() {
      return Future.delayed(Duration(seconds: 2),() => "value1");
    }
    
    Future<String> getValue() {
      return Future.delayed(Duration(seconds: 2), () => "value2");
    }
    
    void main(List<String> arguments) async {
       var stp = Stopwatch()..start();
       await Future.wait([getValue(),getValue1()]);
       stp.stop();
       print("when you execute it with Future.wait: ${stp.elapsedMilliseconds}");
       var stp2 = Stopwatch()..start();
       await getValue1();
       await getValue();
       stp2.stop();
       print("when you execute futures one after an other: ${stp2.elapsedMilliseconds}");
}

But as all the futures are running on the main thread. you cannot consider multithreading.

You can use isolates for better performance. In Dart/flutter, there's no multithreading like Java or c#, etc. Instead, we use isolates. An Isolate is something like a Thread but includes his own memories. The first isolate can't access the memories of the other isolate but those isolates can communicate using ports. To better understand you can check the links below:

explain everything with details

When, why, and how to multithread in Flutter

The boring show Ep 30

I wish that those resources help you.