This repository has been archived by the owner on Nov 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
68 changes: 68 additions & 0 deletions
68
app/src/main/java/com/github/deckyfx/httprequest/ProgressResponseBody.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |