Line data Source code
1 : // Copyright (c) 2021, 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 : import 'dart:async'; 6 : 7 : import 'package:async/async.dart'; 8 : 9 : /// Returns a single-subscription stream that emits the results of [operations] 10 : /// in the order they complete. 11 : /// 12 : /// If the subscription is canceled, any pending operations are canceled as 13 : /// well. 14 0 : Stream<T> inCompletionOrder<T>(Iterable<CancelableOperation<T>> operations) { 15 0 : var operationSet = operations.toSet(); 16 0 : var controller = StreamController<T>( 17 : sync: true, 18 0 : onCancel: () => 19 0 : Future.wait(operationSet.map((operation) => operation.cancel()))); 20 : 21 0 : for (var operation in operationSet) { 22 0 : operation.value 23 0 : .then((value) => controller.add(value)) 24 0 : .onError(controller.addError) 25 0 : .whenComplete(() { 26 0 : operationSet.remove(operation); 27 0 : if (operationSet.isEmpty) controller.close(); 28 : }); 29 : } 30 : 31 0 : return controller.stream; 32 : } 33 : 34 0 : void unawaited(Future<void> f) {}