Skip to content
This repository has been archived by the owner on Nov 26, 2022. It is now read-only.

Commit

Permalink
ProgressResponseBody
Browse files Browse the repository at this point in the history
  • Loading branch information
deckyfx committed Oct 9, 2017
1 parent 0318935 commit a900ab1
Showing 1 changed file with 68 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.github.deckyfx.httprequest;

/**
* Created by decky on 10/9/17.
*/


import java.io.IOException;

import com.github.deckyfx.okhttp3.MediaType;
import com.github.deckyfx.okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
* Created by decky on 5/11/16.
*/
public class ProgressResponseBody extends ResponseBody {

private final ResponseBody responseBody;
private final ProgressListener progressListener;
private BufferedSource bufferedSource;

public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
this.responseBody = responseBody;
this.progressListener = progressListener;
}

@Override
public MediaType contentType() {
return responseBody.contentType();
}

@Override
public long contentLength() {
return responseBody.contentLength();
}

@Override
public BufferedSource source() {
if (bufferedSource == null) {
bufferedSource = Okio.buffer(source(responseBody.source()));
}
return bufferedSource;
}

private Source source(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;

@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
return bytesRead;
}
};
}

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

0 comments on commit a900ab1

Please sign in to comment.