Search code examples
dartdart-async

How can I know when two Streams are done?


I am using Dart's Streams for async events. I have two streams, and I want to know when both streams are complete (aka closed). I'd like to do this with Futures. How do I do it?


Solution

  • A StreamSubscription can return a Future with asFuture. When the stream is closed, the subscription's future completes.

    Use Future.wait to wait for both streams' futures to complete.

    Here is an example:

    import 'dart:async';
    
    Future listenOnTwoStreams(Stream s1, Stream s2) {
      StreamSubscription sub1 = s1.listen((e) => print(e));
      StreamSubscription sub2 = s2.listen((e) => print(e));
      
      Future f1 = sub1.asFuture();
      Future f2 = sub2.asFuture();
      
      return Future.wait([f1, f2]).then((e) => print("all done!"));
    }
    
    void main() {
      StreamController controller1 = StreamController();
      StreamController controller2 = StreamController();
      
      Stream s1 = controller1.stream;
      Stream s2 = controller2.stream;
      
      listenOnTwoStreams(s1, s2);
      
      Timer.run(() {
        controller1.add("1");
        controller2.add("2");
        
        controller1.close();
        controller2.close();
      });
    }