Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart program exits without executing last statement

Tags:

stream

dart

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
}

like image 651
harm Avatar asked Dec 08 '25 05:12

harm


1 Answers

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();
});
like image 180
Nate Bosch Avatar answered Dec 11 '25 05:12

Nate Bosch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!