title: Streaming okhttp response body
body: <p>I'm implementing a <a href="http://www.w3schools.com/html/html5_serversentevents.asp" rel="nofollow noreferrer">Server-Sent Events</a> library using OkHttp. Server Sent Events works by keeping an open HTTP connection to the server on which 'events' can be streamed back to the client. The connection will only close on errors, or if the client explicitly disconnects.</p>
  
  <p>What's the best way to achieve this streaming behaviour using OkHttp? I've attempted to do something like:</p>
  
  <pre class="lang-java prettyprint-override"><code>response.body().source().readAll(new Sink() {
    @Override
    public void write(Buffer source, long byteCount) throws IOException {
      Log.d(TAG, "write(): byteCount = "+byteCount);
    }
  
    @Override
    public void flush() throws IOException {
      Log.d(TAG, "flush()");
    }
  
    @Override
    public Timeout timeout() {
      return Timeout.NONE;
    }
  
    @Override
    public void close() throws IOException {
      Log.d(TAG, "close()");
    }
  });
  </code></pre>
  
  <p>With this approach I will eventually see the log message in <code>write()</code>, but it can sometimes take quite a while (minutes). That makes me think there might be some buffering going on under the hood and I don't get my data until the buffer is flushed.</p>
  
  <p>I've used <code>curl</code> to verify the server is behaving correctly. The data <em>is</em> being sent on time, I'm just not getting my callback when it arrives.</p>
  
  <p>My experience with <code>OkHttp</code> and <code>Okio</code> is very limited, so it's very possible I've messed something up, or have forgotten to set some option. Any help is greatly appreciated! :)</p>