创建流观看列表?

Create a stream watching a list?

我有一个这样的全局列表:

var data = [1,2,3];

我将向其中添加更多元素,每次添加时我都希望通知其他内容 - 我需要流和侦听器。那么我可以创建一个流并在列表发生变化时告诉它 运行 sink.add 吗?

var stream = Stream.fromIterable(data);
stream.listen((item) => print(item));
> 1
> 2
> 3

data.add(4);
> Uncaught Error: Concurrent modification during iteration
data.remove(3);
> Uncaught Error: Concurrent modification during iteration

哦不。我该怎么做才能完成这项工作?

这可能有帮助:

import 'dart:async';

class  ObservableList<T> {
  final _list = <T>[];
  
  final _itemAddedStreamController = StreamController<T>();
  
  final _listStreamController = StreamController<List<T>>();
  
  Stream get itemAddedStream => _itemAddedStreamController.stream;
  
  Stream get listStream => _listStreamController.stream;
  
  
  void add(T value) {
    _list.add(value);
    _itemAddedStreamController.add(value);
    _listStreamController.add(_list);
  }
  
  void dispose() {
    _listStreamController.close();
    _itemAddedStreamController.close();
  }
}

void main() {
  final observableList = ObservableList<int>();
  
  observableList.itemAddedStream.listen((value) => print(value));
  
  observableList.add(1);
  observableList.add(2);
  observableList.add(3);
  observableList.add(4);
}