| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library future_group; |
| 6 |
| 7 import 'dart:async'; |
| 8 |
| 9 /// A completer that waits until all added [Future]s complete. |
| 10 // TODO(rnystrom): Copied from web_components. Remove from here when it gets |
| 11 // added to dart:core. (See #6626.) |
| 12 class FutureGroup<T> { |
| 13 int _pending = 0; |
| 14 Completer<List<T>> _completer = new Completer<List<T>>(); |
| 15 final List<Future<T>> futures = <Future<T>>[]; |
| 16 bool completed = false; |
| 17 |
| 18 final List<T> _values = <T>[]; |
| 19 |
| 20 /// Wait for [task] to complete. |
| 21 Future<T> add(Future<T> task) { |
| 22 if (completed) { |
| 23 throw new StateError("The FutureGroup has already completed."); |
| 24 } |
| 25 |
| 26 _pending++; |
| 27 futures.add(task.then((value) { |
| 28 if (completed) return; |
| 29 |
| 30 _pending--; |
| 31 _values.add(value); |
| 32 |
| 33 if (_pending <= 0) { |
| 34 completed = true; |
| 35 _completer.complete(_values); |
| 36 } |
| 37 }).catchError((e) { |
| 38 if (completed) return; |
| 39 |
| 40 completed = true; |
| 41 _completer.completeError(e.error, e.stackTrace); |
| 42 })); |
| 43 |
| 44 return task; |
| 45 } |
| 46 |
| 47 Future<List> get future => _completer.future; |
| 48 } |
| 49 |
| OLD | NEW |