Dart 异步*阻止函数体执行
将async*添加到listen方法时,它不会执行函数体Dart 异步*阻止函数体执行,dart,Dart,将async*添加到listen方法时,它不会执行函数体 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)); yi
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);
});
}
导入'dart:async';
主(列表参数){
打印('=');
transstream();
}
流intStreamer()异步*{
int c=0;
虽然(c当您使用async*
时,仅当返回的流
获得订户时,才会开始执行该方法。您的代码实际上没有任何意义,因为listen
采用了返回void
的方法。因此,没有人会侦听给定方法返回的流
将自动返回(基于async*
关键字)
我也会正确地重写您的代码,这样您就不用使用listen
而使用wait 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()从intStreamer()返回一个流呢通过听它。我如何使用我的wait for
解决方案从listen的async*回调中获得收益应该足够简单吗?你只需将transstream
标记为async*
,返回流,并像平常一样使用收益
?我已经用一个例子更新了我的答案。是的,这会奏效。Th感谢您的帮助。还有一个疑问,如果intStreamer()它不是异步生成器,而是一个StreamController,它将随机发出事件,因此Wait for will在这里工作similarly@arunized它实际上没有改变任何东西。您仍然可以订阅返回的流
,并做您想做的事情。我建议您在语言教程中阅读更多关于流的内容:好的,谢谢您的帮助
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;
}
}