dart - async* 阻止函数体执行
问题描述
将 async* 添加到监听方法时,它没有执行函数体
import 'dart:async';
main(List<String> args) {
print('====');
tranStream();
}
Stream<int> intStreamer() async* {
int c = 0;
while (c <= 30) {
await Future.delayed(Duration(seconds: 1));
yield c++;
}
}
tranStream() {
intStreamer().listen((event) async* { // If i remove async* from here it will execute print statement
print(event);
});
}
如果我从中删除 async* ,intStreamer().listen
它将执行打印语句。这里发生了什么?
解决方案
当您使用async*
时,该方法只会在返回Stream
的获得订阅者时开始执行。您的代码实际上没有任何意义,因为listen
它采用了返回的方法void
。因此,没有人会监听Stream
给定方法将自动返回的返回值(基于async*
关键字)。
我也会正确地重写你的代码,这样你而不是listen
使用await for
我认为更清楚会发生什么的用法`:
import 'dart:async';
Future<void> main(List<String> args) async {
print('====');
await tranStream();
}
Stream<int> intStreamer() async* {
int c = 0;
while (c <= 30) {
await Future<void>.delayed(const Duration(seconds: 1));
yield c++;
}
}
Future<void> tranStream() async {
await for (final event in intStreamer()) {
print(event);
}
}
tranStream
使用返回流的示例进行更新:
import 'dart:async';
Future<void> main(List<String> args) async {
print('====');
await for (final event in tranStream()) {
print('main got: $event');
}
}
Stream<int> intStreamer() async* {
int c = 0;
while (c <= 30) {
await Future<void>.delayed(const Duration(seconds: 1));
yield c++;
}
}
Stream<int> tranStream() async* {
await for (final event in intStreamer()) {
print('tranStream got: $event');
yield event;
}
}
推荐阅读
- python - 由于 AttributeError,无法区分 3D 中的样条线
- java - 如何使用 FitNesse 测试 Java 类
- html - 我无法让 Rainbow Text 工作。我在这里做错了吗?
- python - 使用 pyfmi 库在 python 中加载 fmu 时出错
- excel - 为什么现在删除重复项会引发错误?
- c# - 在独木舟配置模拟中自动生成节点
- python - 如果正则表达式找不到匹配项,则返回“错误”
- mongodb - 如何用本地数据填充 dockerized MongoDB?
- android - 我无法让我的 android 应用在 react-native 上运行
- laravel - 如何在 wheres 数组中使用运算符