Alpha
Alpha

Reputation: 149

Dart : what happens when two or more tasks are waiting on the same Future

In Dart, when two or more tasks are waiting on the same Future, when the Future completes, do the tasks get notified/run in the order that they did the await i.e. the first to do an await is the first to run.

Is this code guaranteed to output 2

int res = 0;

Future<void> foo1 () async
{
  await Future.delayed(Duration(seconds: 2));
  res = 2;
}


void main() async
{
  await foo1();
  print(res);
}

and what about this code, slightly less obvious

int res = 0;

Future<void> foo1 () async
{
  await Future.delayed(Duration(seconds: 2));
}


Future<void> foo2 (Future<void> f1) async
{
  await f1;
  res = 2;
}

Future<void> foo3 (Future<void> f1) async
{
  await f1;
  res = 3;
}


void main() async
{
  res = 0;
  
  Future<void> f1 = foo1();
  foo3(f1);
  foo2(f1);
  await f1;
  print(res);
}

Upvotes: 2

Views: 78

Answers (2)

lrn
lrn

Reputation: 71783

There is no guarantee that the callbacks get called in the order they were added.

The dart:async library code tries to call the callbacks in that order, but it's best-effort only. There are cases, typically where one callback is added before the future is completed, and the other is added after, where it's possible to get called in a different order, because they are handled by different code paths.

It's not easy to trigger those cases, the timing has to be just right, but it is possible.

In the example here, there are three awaits on the f1 future. It's most likely that the printed value will be 2 (because nothing fancy is happening), but both 3 and 0 are allowed results.

Upvotes: 3

Ska Lee
Ska Lee

Reputation: 46

Code printed 2.

int res = 0;

Future<void> foo1() async {
  await Future.delayed(const Duration(seconds: 2));
  print('foo1 method res 1: $res');
  res = 2;
  print('foo1 method res 2: $res');
}

void main() async {
  await foo1();
  print('last res: $res');
}

🧑‍💻 Code Test Output

foo1 method res 1: 0
foo1 method res 2: 2
last res: 2

Upvotes: 0

Related Questions