Index: lib/src/lazy_stream.dart |
diff --git a/lib/src/lazy_stream.dart b/lib/src/lazy_stream.dart |
new file mode 100644 |
index 0000000000000000000000000000000000000000..545e93d0ec8bb5d5123ac01b020657fb3f4c27b3 |
--- /dev/null |
+++ b/lib/src/lazy_stream.dart |
@@ -0,0 +1,48 @@ |
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
+// for details. All rights reserved. Use of this source code is governed by a |
+// BSD-style license that can be found in the LICENSE file. |
+ |
+library async.lazy_stream; |
+ |
+import "dart:async"; |
+ |
+import "stream_completer.dart"; |
+ |
+/// A [Stream] wrapper that forwards to another [Stream] that's initialized |
+/// lazily. |
+/// |
+/// This class allows a concrete `Stream` to be created only once it has a |
+/// listener. It's useful to wrapping APIs that do expensive computation to |
+/// produce a `Stream`. |
+class LazyStream<T> extends Stream<T> { |
+ /// The callback that's called to create the inner stream. |
+ ZoneCallback _callback; |
+ |
+ /// Creates a single-subscription `Stream` that calls [callback] when it gets |
+ /// a listener and forwards to the returned stream. |
+ /// |
+ /// The [callback] may return a `Stream` or a `Future<Stream>`. |
Lasse Reichstein Nielsen
2015/12/03 11:44:19
We generally recommend against creating a Future<S
nweiz
2015/12/11 00:06:57
The idea is to allow people to use `async` in `cal
Lasse Reichstein Nielsen
2015/12/11 12:33:21
Acknowledged.
|
+ LazyStream(callback()) |
+ : _callback = callback; |
Lasse Reichstein Nielsen
2015/12/03 11:44:19
I would put this on the previous line, there's ple
Lasse Reichstein Nielsen
2015/12/03 11:44:19
Check that callback isn't null:
: _callback = ca
nweiz
2015/12/11 00:06:57
This is contrary to how we treat basically any oth
nweiz
2015/12/11 00:06:57
Done.
|
+ |
+ StreamSubscription<T> listen(void onData(T event), |
+ {Function onError, |
+ void onDone(), |
+ bool cancelOnError}) { |
+ if (_callback == null) { |
+ throw new StateError("Stream has already been listened to."); |
+ } |
+ |
+ // Null out the callback before we invoke it to ensure that even while |
+ // running it this can't be double-listened. |
Lasse Reichstein Nielsen
2015/12/03 11:44:20
comma before "this"? The sentence is hard to read.
nweiz
2015/12/11 00:06:57
Done.
|
+ var callback = _callback; |
+ _callback = null; |
+ var result = callback(); |
+ |
+ var stream = result is Future ? StreamCompleter.fromFuture(result) : result; |
+ assert(stream is Stream); |
Lasse Reichstein Nielsen
2015/12/03 11:44:19
Just make it "Stream stream = ...".
No need to int
nweiz
2015/12/11 00:06:57
Done.
|
+ |
+ return stream.listen(onData, |
+ onError: onError, onDone: onDone, cancelOnError: cancelOnError); |
+ } |
+} |