Flutter FutureGroup
FutureGroup provides us the functionality of combining multiple futures into one single group, which will give the callback at the end when all future tasks work gets completed.
How to implement FutureGroup?
FutureGroup is having an add method that will add the Single Future task in the group.
Add Dependency:
dependencies: async: ^2.4.1
FutureGroup futureGroup = FutureGroup();
futureGroup.add(future1);
futureGroup.add(future2);
futureGroup.add(future3);
Creating the FutureTask
Here I have added three Future Task which will run after given Duration. But this will happen with only single Future, FutureGroup will perform & will give callback once all the Future Task gets completed, means it will provide callback after 6 seconds only not 2 & 4 seconds
void main() {
Future<String> future1 = getData(2);
Future<String> future2 = getData(4);
Future<String> future3 = getData(6);
FutureGroup futureGroup = FutureGroup();
futureGroup.add(future1);
futureGroup.add(future2);
futureGroup.add(future3);
futureGroup.close();
futureGroup.future.then((value) => {print(value)});
}
Future<String> getData(int duration) async {
await Future.delayed(Duration(seconds: duration)); //Mock delay
return "This a test data";
}
Output:
I/flutter ( 5866): [This a test data, This a test data, This a test data] // Called after 6 seconds.
This will provide the list of results in the same sequence which added in the FutureGroup.
If any added future completes with an error, the future will emit that error and the group will be closed, regardless of the state of other futures in the group.
It’s important to call close on FutureGroup as it says
close() → voidSignals to the group that the caller is done adding futures, and so future should fire once all added futures have completed.