Dart program exits without executing last statement

谁说我不能喝 提交于 2021-02-09 11:06:06

问题


I'm trying to understand Streams and wrote some code. Everything seems to work, the program exits with status code 0. But it doesn't print the 'loop done' and 'main done' strings. I can't figure out why.

import 'dart:async';

Stream<int> countStream(int to) async* {
      for (int i = 1; i <= to; i++) {
              yield i;
      }
}

class Retry {
    StreamController<int> _outgoing;

    Retry(Stream<int> incoming) {
        _outgoing = StreamController<int>();
        _outgoing.addStream(incoming);
    }

    Future<void> process() async {
        await for (final i in _outgoing.stream) {
            print("got $i");
        }
        print('loop done'); // Not printed
    }
}

void main() async {
  var stream = countStream(4);
  var retry = Retry(stream);
  await retry.process();
  print('main done'); // Not printed
}


回答1:


The _outgoing.stream is never closed, so code after the await for will never execute. The VM does notice that there also won't be any new events on that stream so nothing else will ever happen, and it can exit. You could fix the bug with:

_outgoing.addStream(incoming).whenComplete(() {
    _outgoing.close();
});


来源:https://stackoverflow.com/questions/56169492/dart-program-exits-without-executing-last-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!