将 Stream<Item> 转换为 Stream<List<Item>>

Transform Stream<Item> to Stream<List<Item>>

我尝试通过 Stream 获取文件夹中的所有文件。

Directort(path).list() returns Stream<FileSystemEntity>.

我要returnsStream<List<FileSystemEntity>>.

示例:

1 => 1
2 => 1,2
3 => 1,2,3

您可以使用包装器对象来存储列表

试试这个作为起点

class StreamToStreamList<T> {
  StreamToStreamList(this._parent);

  final Stream<T> _parent;
  final _values = <T>[];

  Stream<List<T>> toStream() async* {
    await for (final value in _parent) {
      _values.add(value);
      yield _values;
    }
  }
}

  final result = Directory(path)
      // get subentries of the path dir
      .list()
      // getting only sub-directories (assumtion is that you are interested in those only)
      .where((dir) => dir is Directory)
      // casting them to Directory object
      .cast<Directory>()
      // processing each dir getting its sub-entries 
      .map((dir) => dir.listSync())
  ;

编辑:当您希望结果将文件也作为流中列表的单个元素时的情况:

  final result = Directory(path)
      // get sub-entries of the path dir
      .list()
      // processing each entry so dir entry -> list of dir sub entries and file entry -> list containing one file as single element   
      .map((dir) {
        if(dir is Directory) {
          return dir.listSync();
        } else {
          return [dir];
        }
      })
  ;
来自 rxdart

scan 运算符是最佳答案
https://pub.dev/documentation/rxdart/latest/rx/ScanExtension/scan.html https://rxjs.dev/api/operators/scan

Stream<FileSystemEntity> source$ = ...;

Stream<List<FileSystemEntity>> result$ = source$.scan(
    (acc, element, _) => [...acc, element],
    [],
);