Search code examples
dartdart-async

Channel primitive in dart?


Is there a channel primitive in Dart as there is in Go for example? The closest I found is StreamIterator.

The use case would be to allow a consumer to asynchronously process values one by one. Additionally, if there is no value, it should just wait.


Solution

  • You can do this with streams

    import 'dart:async' show Stream, StreamController;
    
    main() {
      StreamController<int> sc = new StreamController<int>();
    
      sc.stream.listen((e) => print(e));
    
      for(int i = 0; i < 10; i++) {
        sc.add(i);
      }
    }
    

    Try it in DartPad

    See also

    You can't "just wait" in Dart, especially in the browser.

    There are also async* generator functions available in Dart to create streams. See for example Async/Await feature in Dart 1.8

    A "naive" translation form await for(var event in someStream)

    import 'dart:async';
    
    main() {
      StreamController<int> sc = new StreamController<int>();
    
      startProcessing(sc.stream);
    
      for(int i = 0; i < 10; i++) {
        sc.add(i);
      }
    }
    
    Future startProcessing(Stream stream) async {
      StreamSubscription subscr;
      subscr = stream.listen((value) {
        subscr.pause();
        new Future.delayed(new Duration(milliseconds: 500)).then((_) {
          print('Processed $value');
          subscr.resume();
        });
      });
      //await for(int value in stream) {
      //  await new Future.delayed(new Duration(milliseconds: 500)).then((_) {
      //    print('Processed $value');
      //  });
      //} 
    }
    

    The actual implementation takes a different approach

    The way the await-for loop is implemented uses a one-event buffer (to avoid repeatedly pausing and resuming).

    See https://github.com/dart-lang/sdk/issues/24956#issuecomment-157328619