我有一个这样的全局列表:
var data = [1,2,3];
我将向它添加更多的元素,每次这样做时,我都希望通知其他东西—我需要一个流和侦听器。所以我可以制造一条小溪,让它往下沉。在列表发生变化时添加?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);
}