OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2015, 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 async.lazy_stream; | |
6 | |
7 import "dart:async"; | |
8 | |
9 import "stream_completer.dart"; | |
10 | |
11 /// A [Stream] wrapper that forwards to another [Stream] that's initialized | |
12 /// lazily. | |
13 /// | |
14 /// This class allows a concrete `Stream` to be created only once it has a | |
15 /// listener. It's useful to wrapping APIs that do expensive computation to | |
16 /// produce a `Stream`. | |
17 class LazyStream<T> extends Stream<T> { | |
18 /// The callback that's called to create the inner stream. | |
19 ZoneCallback _callback; | |
20 | |
21 /// Creates a single-subscription `Stream` that calls [callback] when it gets | |
22 /// a listener and forwards to the returned stream. | |
23 /// | |
24 /// 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.
| |
25 LazyStream(callback()) | |
26 : _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.
| |
27 | |
28 StreamSubscription<T> listen(void onData(T event), | |
29 {Function onError, | |
30 void onDone(), | |
31 bool cancelOnError}) { | |
32 if (_callback == null) { | |
33 throw new StateError("Stream has already been listened to."); | |
34 } | |
35 | |
36 // Null out the callback before we invoke it to ensure that even while | |
37 // 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.
| |
38 var callback = _callback; | |
39 _callback = null; | |
40 var result = callback(); | |
41 | |
42 var stream = result is Future ? StreamCompleter.fromFuture(result) : result; | |
43 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.
| |
44 | |
45 return stream.listen(onData, | |
46 onError: onError, onDone: onDone, cancelOnError: cancelOnError); | |
47 } | |
48 } | |
OLD | NEW |