在 m4 更新后,StreamController.broadcast() 被删除,我发现 asBroadcastStream 不能被多次调用。这意味着您必须像在 Ugly 类中那样存储流,而不是像在 Pretty 类中那样仅使用 getter。
这是设计使然,还是我做错了?
void main() {
Pretty p = new Pretty();
//This does not work.
p.onChange.listen((n) => print(n));
//This second call throws: "Bad state: Stream already has subscriber". Why?
p.onChange.listen((n) => print(n));
//This does work.
Ugly u = new Ugly();
u.onChange.listen((n) => print(n));
u.onChange.listen((n) => print(n));
}
class Pretty{
StreamController<int> _streamCtrl = new StreamController<int>();
Stream<int> get onChange => _streamCtrl.stream.asBroadcastStream();
}
class Ugly{
StreamController<int> _streamCtrl = new StreamController<int>();
Stream<int> _onChange;
Stream<int> get onChange => _onChange;
Ugly(){
_onChange = _streamCtrl.stream.asBroadcastStream();
}
}