Jitesh Mohite
Jitesh Mohite

Reputation: 34250

Flutter: Combine Multiple Future<T> Tasks

How we can merge multiple FutureTask so that we can get a callback for all at the same response.

We use Future<T> like

Future<String> getData(int duration) async {
  await Future.delayed(Duration(seconds: duration)); //Mock delay
  return "This a test data for duration $duration";
}

Call above method like getData(2).then((value) => print(value));

If we want to call multiple Future Task, then how can we do that?

Upvotes: 16

Views: 10959

Answers (2)

Sourav9063
Sourav9063

Reputation: 329

To execute all futures concurrently, use Future.wait This takes a list of futures and returns a future of lists: Suppose you have these futures.

class CovidAPI {
  Future<int> getCases() => Future.value(1000);
  Future<int> getRecovered() => Future.value(100);
  Future<int> getDeaths() => Future.value(10);
}

You can get all the futures together using Future.wait([list of futures])

final api = CovidAPI();
final values = await Future.wait([
    api.getCases(),
    api.getRecovered(),
    api.getDeaths(),
]);
print(values); // [1000, 100, 10]

This is ideal when the futures are independent, and they don't need to execute sequentially. Source : https://codewithandrea.com/videos/top-dart-tips-and-tricks-for-flutter-devs/

Upvotes: 19

Jitesh Mohite
Jitesh Mohite

Reputation: 34250

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.

Upvotes: 6

Related Questions