How to use async/await in Dart for parallel processing - flutter

In C# I can use async and await to process tasks in parallel. I can kick off an asynchronous task, do other things, and finally await for the asynchronous task to complete.
var t = myFunctionAsync();
executeTask1();
executeTask2();
await t;
How can I do this in dart/flutter?

Reference: async-await
void main() async {
var t = myFunctionAsync();
executeTask1();
executeTask2();
await t;
}
Future<int> myFunctionAsync() async {
await Future.delayed(const Duration(seconds: 2));
return 2;
}
void executeTask1() {
// do something
}
void executeTask2() {
// do something
}

void someFunction () async{
executeTask1();
executeTask2();
await executeTask3();
}

Related

i have question about asynchronous programming at flutter

void main() async {
check();
print('end');
}
Future check() async {
var version = lookUpVersion();
print(version);
}
int lookUpVersion() {
return 12;
}
void main() async {
check();
print('end');
}
Future check() async {
var verion = await lookUpVersion();
print(version);
}
int lookUpVersion() {
return 12;
}
These two code only have one difference, await keyword.
I wonder that why not did they wait for main function code? even I used Future+async keyword at first code.
Can you explain about this?
The async and await keywords provide a declarative way to define asynchronous functions and use their results.
For first one - result will be
//12
//end
For second one - result will be
//end
//12
Which means if you add await it will become asynchronous.

Semaphore in flutter

Code:
void _test() {
print(1);
Timer.run(() {
print(2);
});
print(3);
}
Print 1 3 2.
I want print 1 2 3.
In iOS I can use Semaphore, how can I do this in flutter?
Awaiting for a method to complete can be written inside a future
void _test() async{
print(1);
Future.delayed(Duration(seconds : 0), (){
print(2);
});
print(3);
}
//Output 1 3 2
void _test() async{
print(1);
await Future.delayed(Duration(seconds : 0), (){
print(2);
});
print(3);
}
//Output 1 2 3
In the second example the await will wait for the future to complete and then move to the next task
Thanks #jamesdlin, I solved with his comment, below is desired code:
void _test() async {
print(1);
Completer<void> completer = Completer();
Timer.run(() {
print(2);
completer.complete();
});
await completer.future;
print(3);
}
Timer.run() basically tells the program that here is a piece of code that should be executed but I don't care if it finishes before it reaches the code outside of this block.
If you want to wait a bit, use Future.delayed:
runAsyncMethod() async {
print("1");
await Future.delayed(Duration(seconds: 3), () {print("2");});
print("3");
}

How do you check if an async void method is completed in Dart?

How do you check if an async void method is completed in Dart?
Method 1:
await voidFoo();
print("the above function was completed");
Future<void> voidFoo() async{
await Future.delayed(Duration(seconds:1));
}
Method 2:
Using a boolean variable like this,
bool isCompleted = false;
...
await voidFoo();
Future<void> voidFoo() async{
await Future.delayed(Duration(seconds:1));
isCompleted = true; //assuming isCompleted can be accessed here
}
There are too many methods to do this
i prefer to do this
Future<void> myFunction() async {
await Future.delayed(Duration(seconds: 3)); // your future operation
}
main() async {
await myFunction();
print("finished");
}
You can use dart Completer.
import 'dart:async';
void main() async {
final completer = Completer<String>();
Future<String> getHttpData()async{
return Future.delayed(const Duration(seconds: 1), () => "Future Result");
}
Future<String> asyncQuery()async {
final httpResponse = await getHttpData();
completer.complete(httpResponse);
return completer.future;
}
print('IsCompleted: ${completer.isCompleted}');
await asyncQuery();
print('IsCompleted: ${completer.isCompleted}');
}
Result;
IsCompleted: false
IsCompleted: true

How can i get time of async function execution?

I need to do some actions if my http requests lasts more than 1 sec (But not stop it, so i can't use duration property)
How is this possible in Dart?
You can achieve this with a Timer from dart:async:
import 'dart:async';
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 5));
return 'data';
}
Future<void> main() async {
Timer timer;
timer = Timer(Duration(seconds: 1), () => print("Timer expired!"));
final data = await fetchData();
timer.cancel();
print(data);
}

How to use Future Delayed

I have 2 functions. I want to run them one by one but while the first function is done, the second function must wait for 1-2 seconds. I tried Future.delayed for this but it did not work. It changes nothing.
void kartat(int tip, int deger, int mainid, List mycards) {
masadakicards.add(cardbank[mainid]);
print("kart atıldı");
rakipkartat(51);
}
void rakipkartat(int mainid) {
new Future.delayed(Duration(seconds: 1), () {
// deleayed code here
masadakicards.add(cardbank[mainid]);
print("ann");
});
}
A way that you can achieve this is by using await Future.delayed
make sure that your method is returns a Future
Future<void> start() async {
await foo();
await Future.delayed(Duration(seconds: 2));
await bar();
}
Future<void> foo() async {
print('foo started');
await Future.delayed(Duration(seconds: 1));
print('foo executed');
return;
}
Future<void> bar() async {
print('bar started');
await Future.delayed(Duration(seconds: 1));
print('bar executed');
return;
}
expected:
foo started
- waits 1 second -
foo executed
- waits 2 seconds -
bar started
- waits 1 second -
bar executed
Following your methods
Please note that the method that gets executed after the delay also needs to include async and await, otherwise the method will run synchronously and not await the Future.
Future<void> start() async {
foo();
}
void foo() {
Future.delayed(Duration(seconds: 2), () async {
// do something here
await Future.delayed(Duration(seconds: 1));
// do stuff
});
}
Not sure if your overall approach is appropriate (can't tell from this), however,
Future<void> rakipkartat(int mainid) async { should do.
I guess it would be better if you create both and the calling function as Future and then call the functions with await kartet(); await rakipkartat()
By the way, implementing my 1st paragraph also requests that the calling function is a Future or at least handles the call as a Future.