gsk
gsk

Reputation: 43

Select Future or waitAny in Dart?

I understand that Future.wait takes a list of futures and returns a list of completed futures when all the futures in the list have completed.

Is there a way in Dart to block and wait until any future in a list has completed rather than waiting for them all to complete?

Upvotes: 4

Views: 203

Answers (1)

lrn
lrn

Reputation: 71873

Not really. We could add a Future.waitAny (where the existing one is implicitly a waitAll).

The functionality is simple:

Future waitAny(Iterable<Future> futures) {
  var completer = new Completer();
  for (var f in futures) {
    f.then((v) { 
      if (!completer.isCompleted) completer.complete(v);
    }, onError: (e, s) {
      if (!completer.isCompleted) completer.completeError(e, s);
    });
  }
  return completer.future;
}

It does ignore any errors on all the other futures. On the other hand, it also ignores the non-error results, so I guess it's fine.

We lack a way to cancel a future when we no longer care for the result.

Upvotes: 3

Related Questions