我在取消使用 Stream.periodic 构造函数创建的流时遇到问题。下面是我尝试取消流。但是,我很难从内部作用域中提取“计数”变量。因此,我无法取消订阅。
import 'dart:async';
void main() {
int count = 0;
final Stream newsStream = new Stream.periodic(Duration(seconds: 2), (_) {
return _;
});
StreamSubscription mySubscribedStream = newsStream.map((e) {
count = e;
print(count);
return 'stuff $e';
}).listen((e) {
print(e);
});
// count = 0 here because count is scoped inside mySubscribedStream
// How do I extract out 'count', so I can cancel the stream?
if (count > 5) {
mySubscribedStream.cancel();
mySubscribedStream = null;
}
}
Run Code Online (Sandbox Code Playgroud) 我知道Stream.pipe通常如何用于读取和写入文件,但是将它与 StreamController 和自定义流一起使用的好例子是什么?
编辑:我想出了一个关于如何使用的示例Stream.pipe,但是当运行此代码时,屏幕上没有任何输出。我希望数组通过变压器,将每个数字加倍,将输出通过管道传输到第二个控制器,然后将加倍的数字输出到屏幕。但是,我没有看到任何结果。
import 'dart:async';
var stream = Stream.fromIterable([1, 2, 3, 4, 5]);
void main() {
final controller1 = new StreamController();
final controller2 = new StreamController();
final doubler =
new StreamTransformer.fromHandlers(handleData: (data, sink) {
sink.add(data * 2);
});
controller1.stream.transform(doubler).pipe(controller2);
controller2.stream.listen((data) => print(data));
}
Run Code Online (Sandbox Code Playgroud) dart ×2