[英]Yield another broadcast stream with Dart
I am trying to yield*
a broadcast stream but for some reason, it does not work as I expected.我正在尝试
yield*
广播 stream 但由于某种原因,它没有按我的预期工作。
The Firebase/FlutterFire library seems to be doing it that way. Firebase/FlutterFire 库似乎就是这样做的。
import 'dart:async';
final controller = StreamController<int>.broadcast();
Stream<int> getStream() async* {
yield 1;
yield* controller.stream;
}
void main() {
controller.add(0);
getStream().listen(
(event) => print('BC Event: $event'),
onDone: () => print('BC Done'),
onError: (error) => print(error),
);
controller.add(2);
controller.close();
}
Expected:预期的:
BC Event: 1
BC Event: 2
BC Done
Actual:实际的:
BC Event: 1
BC Done
Any idea?任何想法?
i think the problems is that you closes the listen event too soon, before the stream can return the second value我认为问题在于您在 stream 可以返回第二个值之前过早关闭监听事件
i tested with a timer and it worked我用计时器测试过,它有效
import 'dart:async';
final controller = StreamController<int>.broadcast();
Stream<int> getStream() async* {
yield 1;
yield* controller.stream;
}
void main() async {
controller.add(0);
getStream().listen(
(event) => print('BC Event: $event'),
onDone: () => print('BC Done'),
onError: (error) => print(error),
);
await Future.delayed(Duration(seconds: 1));
controller.add(2);
controller.add(3);
controller.add(4);
controller.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.