Search code examples
dartstreampipesink

What is the difference between using Sink and Pipe with Streams in Dart?


import "dart:async";
import "dart:html";

void main() async {
  InputElement addStream = querySelector("#addstream");

  Stream<int> aStream = _someStream();
  StreamController<int> sc = StreamController();

  sc.stream.listen((e) => print(e));

  addStream.onClick.listen((e) {
  sc.sink.addStream(aStream);  // streamcontroller brings in stream through the sink
  // aStream.pipe(sc);   // stream going into streamcontroller through the sink
  });
}

In the code above, sc.sink.addStream(aStream) seems to use the sink method to add aStream to StreamController sc. Under that, aStream uses pipe to get added to StreamController sc.

Both methods seem to do the same thing. It seems to me that using one method over the other is simply style. If you are using a Stream, pipe it to the StreamController. If you are using a StreamController, sink a Stream to it. Is there a particular reason to use one versus the other?


Solution

  • aStream.pipe(sc) will close() the stream controller after the stream is finished. With sc.addStream(aStream) the controller will still be open after the stream is done, so you can add more events or other streams.

    The call to Stream.pipe in this case would be identical to sc.addStream(aStream).then((_) sc.close());