hoangquyy
hoangquyy

Reputation: 2063

Async/Await in Dart

I'm making a Flutter app that using asynchronous a lot but it not working like how I understand about it. So I have some question about async and await in dart. Here is an example:

Future<int> someFunction() async {
  int count = 0;
  for (int i=0; i< 1000000000;i ++) {
    count+= i;
  }
  print("done");
  return count;
}

Future<void> test2() async {
  print("begin");
  var a = await someFunction();
  print('end');
}

void _incrementCounter() {
  print("above");
  test2();
  print("below");
}

test2() function will take a lot of time to done. right? So what i want is when test2 keep his work running until done, everything will keep running and not wait for test2().

When i run the function _incrementCounter(), it show the result:

above begin done below end

The problem is it didn't show "below" right away but it wait until someFunction() done.

This is result i want:

above begin below done end

Upvotes: 1

Views: 1920

Answers (1)

julemand101
julemand101

Reputation: 31209

This is the expected behavior since this change in Dart 2.0 which can be found in the changelog:

(Breaking) Functions marked async now run synchronously until the first await statement. Previously, they would return to the event loop once at the top of the function body before any code runs (issue 30345).

Before I give the solution I want to note you that async code are not running in another thread so the concept of:

keep his work running until done, everything will keep running and not wait for test2()

Is fine but at some point your application are going to wait for test2() to finish since it is spawned as a task on the job queue where it will not leave other jobs to run before it is done. If you want the experience of no slowdown you want to either split the job into multiple smaller jobs or spawn an isolate (which are running in another thread) to run the calculation and later return the result.

Here is the solution go get your example to work:

Future<int> someFunction() async {
  int count = 0;
  for (int i=0; i< 1000000000;i ++) {
    count+= i;
  }
  print("done");
  return count;
}

Future<void> test2() async {
  print("begin");
  var a = await Future.microtask(someFunction);
  print('end');
}

void _incrementCounter() {
  print("above");
  test2();
  print("below");
}

main() {
  _incrementCounter();
}

By using the Future.microtask constructor we are scheduling the someFunction() to be running as another task. This makes it so the "await" are going to wait since it will be the first true instance of an async call.

Upvotes: 7

Related Questions