Idiomatic streams in Dart?

Viewed 264

In playing with Dart, particularly the dart:io library, I've found myself doing weird things with Streams to allow multiple listeners.

For example, I want to emulate the handler-stack pattern found in a number of Node libraries (like Connect & Express). To do so, I need to be able to set up multiple listeners on the request (and response), which means producing a broadcast stream from the request.

This cannot be the only thing I pass around becuase it does not maintain the properties of the request object (such as the response).

handleRequest (HttpRequest request) {
  var stream = request.asBroadcastStream();
  // pass stream *and* request to the handlers
}

An example handler, showing the problem, might look like this:

log (HttpRequest request, Stream stream) {
  DateTime start = new DateTime.now();
  stream.listen(null,
    onDone: () {
      DateTime finish = new DateTime.now();
      print("${request.method} ${request.uri} -> ${request.response.statusCode} ${finish.difference(start).inMilliseconds}ms");
    });
}

What's the idiomatic way of doing this kind of thing? I don't want to force Dart to conform to my JavaScriptish way.

1 Answers
Related