Tracking OkHttp Download Progress

Anton Rieder just contributed an OkHttp code sample that monitors a download’s progress using an interceptor. With it, you get a callback as bytes arrive:

  interface ProgressListener {
    void update(long bytesRead, long contentLength, boolean done);

I like this example because it’s all layered decorators:

  • The Interceptor puts code between application-and-OkHttp, or OkHttp-and-network.
  • The ResponseBody augments the response body to support progress tracking.
  • The Source does the work: updating the progress listener as bytes are delivered from network to application.

In each case, the adaptable interface is deliberately limited. Decorating okio.Source is easy! To contrast, InputStream is hostile to decoration.