Chromium Code Reviews| Index: sdk/lib/_internal/pub/lib/src/utils.dart |
| diff --git a/sdk/lib/_internal/pub/lib/src/utils.dart b/sdk/lib/_internal/pub/lib/src/utils.dart |
| index 6a048cf1612a5184c6c0b0d309dc4cec16c561c9..aae5bd14fed7dfdf0e43b372699127c8d5294b20 100644 |
| --- a/sdk/lib/_internal/pub/lib/src/utils.dart |
| +++ b/sdk/lib/_internal/pub/lib/src/utils.dart |
| @@ -168,6 +168,39 @@ void chainToCompleter(Future future, Completer completer) { |
| onError: (e) => completer.completeError(e)); |
| } |
| +/// Ensures that [stream] can emit at least one value successfully (or close |
| +/// without any values). |
| +/// |
| +/// For example, reading asynchronously from a non-existent file will return a |
| +/// stream that fails on the first chunk. In order to handle that more |
| +/// gracefully, you may want to check that the stream looks like it's working |
| +/// before you pipe the stream to something else. |
| +/// |
| +/// This lets you do that. It returns a [Future] that completes to a [Stream] |
| +/// emitting the same values and errors as [stream], but only if at least one |
| +/// value can be read successfully. If an error occurs before any values are |
| +/// emitted, the returned Future completes to that error. |
| +Future<Stream> validateStream(Stream stream) { |
| + var completer = new Completer<Stream>(); |
| + var controller = new StreamController(); |
|
nweiz
2013/08/12 20:26:31
Make this sync? Since [stream] will already be asy
Bob Nystrom
2013/08/12 21:45:00
Good call. Done.
|
| + |
| + stream.listen((value) { |
| + // We got a value, so the stream is valid. |
| + if (!completer.isCompleted) completer.complete(controller.stream); |
| + controller.add(value); |
| + }, onError: (error) { |
| + // We got an error before any values, so the stream is invalid. |
| + if (!completer.isCompleted) completer.completeError(error); |
|
nweiz
2013/08/12 20:26:31
If we get an error first, we should cancel our sub
Bob Nystrom
2013/08/12 21:45:00
Done.
|
| + controller.addError(error); |
| + }, onDone: () { |
| + // It closed with no errors, so the stream is valid. |
| + if (!completer.isCompleted) completer.complete(controller.stream); |
| + controller.close(); |
| + }); |
| + |
| + return completer.future; |
| +} |
| + |
| // TODO(nweiz): remove this when issue 7964 is fixed. |
| /// Returns a [Future] that will complete to the first element of [stream]. |
| /// Unlike [Stream.first], this is safe to use with single-subscription streams. |