Dart / Flutter:错误“已经收听了流。”&&“await for”内部fa“for循环”失败

问题描述 投票:0回答:1

好的人,

我可能在这里遗漏了一些东西:

这段代码是虚构的(这是一个过于简单化,为了每个人的方便),但给出了这个想法:

_map.keys.forEach((key) async {
   _bloc.sink.add(_map[key]);
await for (String _string in _bloc.stream) {
  _newMap.putIfAbsent(key, ()=> _string);
 }
});

要么

Stream.fromIterable(_map.keys).forEach((day) async {
    _bloc.sink.add(_map[key]);
await for (String _string in _bloc.stream) {
  _newMap.putIfAbsent(key, ()=> _string);
 }
});

with StreamController <...>。broadcast();溪流似乎很健康:

第一个:_Future hashCode:817453996 isBroadcast:true isEmpty:_Future last:_Future length:_Future runtimeType:Type(_BroadcastStream <...>)single:_Future _awaiter:null _generator:null _controller:_AsyncBroadcastStreamController

不返回此错误:

第一种:未处理的异常:\ nBad状态:Stream已被监听。[...] hashCode:644468606 isBroadcast:false isEmpty:未处理的异常:\ nBad状态:Stream已被监听。[...] last:未处理的异常:\ nBad状态:Stream已被侦听。[...] length:未处理的异常:\ nBad状态:Stream已被侦听。[...] runtimeType:Type(_ControllerStream <...> )single:未处理的异常:\ nBad状态:Stream已被监听。[...] _awaiter:null _generator:null _controller:_AsyncStreamController

在这两种情况下,都不起作用。

我打算做的是(在for循环中)在接收器中发送一个集合,

一个集团会做一些工作并返回流中的另一个集合,

我从调试中看到的是循环只是继续向接收器发送内容。

我不确定那是因为:

...

1)循环不等待“等待”

并导致错误“流已经听”

2)反之亦然“await for”因错误而无法收听流

(或因为广播可能会丢失事件)因此循环保持循环(?);

...

我更倾向于关于第一个,但它应该根据这个POST工作

我究竟做错了什么?

弗朗西斯科,提前谢谢你

dart flutter stream iteration
1个回答
1
投票

这似乎不止一次调用stream.listen。尝试将_bloc.stream分配给for循环之外的变量。

var stream = _bloc.stream;


_map.keys.forEach((key) async {
  _bloc.sink.add(_map[key]);
await for (String _string in stream) {
 _newMap.putIfAbsent(key, ()=> _string);
}
});
© www.soinside.com 2019 - 2024. All rights reserved.