For it, FutureGroup can be used to combine multiple streams
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.
Dependency:
dependencies:
async: ^2.4.1
How to implement FutureGroup?
FutureGroup futureGroup = FutureGroup();
futureGroup.add(future1);
futureGroup.add(future2);
futureGroup.add(future3);
Use:
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.
Note: This will be called only once when all the Future Task gets completed, here it will run after 6 seconds.
await
beforegetData(2)
– EclatFuture.wait()
– Swayne