title: how to send http response using stream
body: <p>I would like to have simple API in my http server so everytime I write to HttpResponse I use stream.</p>
  
  <p>so I convert all object into stream, ie object->json->stream</p>
  
  
  
  <pre class="lang-dart prettyprint-override"><code>Stream&lt;List&lt;int&gt;&gt; toStream(Object value) {
      var json = JSON.encode(value);
      var controller = new StreamController&lt;List&lt;int&gt;&gt;(onListen: () =&gt; UTF8.encode(json));
      return controller.stream;
  }
  </code></pre>
  
  <p>and later </p>
  
  <pre class="lang-dart prettyprint-override"><code>(response as HttpResponse).addStream(toStream({"a": 1, "B": 2})
  .then(() =&gt; response.flush())
  .catchError((e, stack) {
      _logger.error("Handling ${context.path} finished with an error: $e");
      _logger.debug(stack.toString());
  })
  .whenComplete(() =&gt; response.close());
  </code></pre>
  
  <p>but I get error</p>
  
  <pre class="lang-dart prettyprint-override"><code>Uncaught Error: Bad state: StreamSink is bound to a stream
  Stack Trace: 
  #0      _StreamSinkImpl.close (io_sink.dart:122)
  #1      _HttpOutboundMessage.close (http_impl.dart:481)
  </code></pre>
  
  <p>Im not sure what I am doing wrong here. I saw examples where File's input stream was piped to response but I cannot make it work either. </p>
  
  <p>any help appreciated!</p>