问题描述
我试着用Dart Streams包装我的头。特别是此具有以下代码行:
I am trying to wrap my head around Dart Streams. In particular this example of the command line utility cat
has the following lines of code:
Stream<List<int>> stream = new File(path).openRead();
// Transform the stream using a `StreamTransformer`. The transformers
// used here convert the data to UTF8 and split string values into
// individual lines.
return stream
.transform(UTF8.decoder)
.transform(const LineSplitter())
.listen((line) {
if (showLineNumbers) {
stdout.write('${lineNumber++} ');
}
stdout.writeln(line);
}).asFuture().catchError((_) => _handleError(path));
-
; T>
asStream< List< int>>
让我有点困惑。为什么不声明为Stream< int>
。 List<>类型如何使它不同。如果是列表,订阅者事件是否以某种方式缓冲?
The declaration of the
Stream<T>
asStream<List<int>>
has me a bit confused. Why is it not declared as aStream<int>
. How does the List<> type make this different. Are the subscriber events buffered in some way if it is a List?
什么类型(如< T>
)传递给第一个变换?是 int
还是列表< int>
?
What Type (as in <T>
) is passed to the first transform? Is it an int
or a List<int>
?
传递给每个下一个转换的类型以及决定它们类型的类型。
What type is passed to each of the next transforms and what determines their type.
此示例在将转换结果传递给下一个转换之前读取整个文件吗?如果是这样,是否有一个例子某处如何流类似这个Node问题的非常大的文件
Does this example read the entire file before passing the results of the transform to the next transform? If so, is there an example somewhere of how to Stream very large files similar to this Node question Parsing huge logfiles in Node.js - read in line-by-line
推荐答案
- 好问题。
-
UTF8
是一个,扩展了Codec< String,List< int>>
。因此,是一个Converter< List< int>,String>
以List< int>
li> 是一个Converter< String,List< String>>
。因此,它需要String
作为参数。.transform(const LineSplitter())
的结果流是发送每一行的Stream< String>
。 -
File.openRead
在将第一个字节写入流之前不会读取整个文件。因此,处理大型文件没有问题。
- Good question.
UTF8
is a Utf8Codec that extendsCodec<String, List<int>>
. So UTF8.decoder is aConverter<List<int>, String>
that takesList<int>
as parameter.- LineSplitter is a
Converter<String, List<String>>
. So it takesString
as parameter. The resulting stream of.transform(const LineSplitter())
is aStream<String>
where each line is sent. File.openRead
doesn't read the entire file before writing the first bytes to the stream. So there's no problem to deal with large files.
这篇关于Stream< List< int>>和Stream< int>在Dart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!