gpt4 book ai didi

dart - asBroadcastStream 不能被多次调用

转载 作者:行者123 更新时间:2023-12-03 02:43:05 24 4
gpt4 key购买 nike

在 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();
}
}

最佳答案

目前没有更好的方法来做到这一点。

这是邮件列表中的线程,包含更多信息:https://groups.google.com/a/dartlang.org/forum/#!searchin/misc/asBroadcastStream%7Csort:relevance/misc/KJrKH5-bNkU/CjpIpEP_EpgJ

在邮件中,我说:

使用 r21499,我们删除了 StreamController.broadcast 构造函数。

The StreamController.broadcast streams had nasty properties that could easily lead to missed events and similar hard-to-debug conditions. We initially added this class for the html-library, but ended up not needing it there. By removing this class we can have a much cleaner contract for Streams. We still kept the asBroadcastStream method. Its behavior is slightly different and saner than the one of StreamController.broadcast. In most cases you can try to migrate to asBroadcastStream if you need to attach multiple listeners.

关于dart - asBroadcastStream 不能被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16057001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com