首页 > 解决方案 > 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它将执行打印语句。这里发生了什么?

标签: dart

解决方案


当您使用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;
  }
}

推荐阅读