Igor F.
Igor F.

Reputation: 2699

How to assign results of futures in Dart depending on which future produced them?

In Dart, I want to run several costly functions, which are independent of each other, and assign the results to my variables, depending on which function produced them. Roughly a parallel version of this:

double x = getX();
double y = getY();

I'm thinking of something like this:

double x, y;
Future.wait([
  futureGetX(),
  futureGetY()
]).then((List results) {
  results.foreach((r) {
    // if(r is produced by futureGetX) x = r;
    // if(r is produced by futureGetY) y = r;
  }); 
});

and I don't know how to implement this is produced by part. A way would be to wrap the result of each function in a different class and, in the then part, check the class of the result:

if(r is wrapperForX) x = r.getValue();
if(r is wrapperForY) y = r.getValue();

but this seems very inelegant to me. Any suggestions?

Upvotes: 0

Views: 878

Answers (4)

Dafe Šimonek
Dafe Šimonek

Reputation: 351

Another way would be to use FutureGroup from async package, FIFO behavior for the result list is documented: https://www.dartdocs.org/documentation/async/1.13.3/async/FutureGroup-class.html

Upvotes: 0

lrn
lrn

Reputation: 71693

To wait for Futures in parallel, you use Future.wait, as you already noticed. The results in the list returned (asynchronously) by Future.wait are in the same order as the original futures, so instead of using forEach you can just do:

x = results[0];
y = results[1];

Upvotes: 0

Igor F.
Igor F.

Reputation: 2699

Thanks to Randal I found a solution:

Future.wait([
  () async { x = await futureGetX(); } (),
  () async { y = await futureGetY(); } ()
]);

Upvotes: 0

Randal Schwartz
Randal Schwartz

Reputation: 44081

Untested, but I think I got this. :)

Use closures:

Future.wait([
  () => { x = await futureGetX()},
  () => { y = await futureGetY()},
]);

Upvotes: 1

Related Questions