Skip to content
This repository was archived by the owner on Jul 25, 2024. It is now read-only.

Commit 471fcff

Browse files
Sam1301kunall17
authored andcommitted
Add custom upload progress RequestBody.
1 parent f638161 commit 471fcff

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package com.zulip.android.networking;
2+
3+
import java.io.IOException;
4+
5+
import okhttp3.MediaType;
6+
import okhttp3.ResponseBody;
7+
import okio.Buffer;
8+
import okio.BufferedSource;
9+
import okio.ForwardingSource;
10+
import okio.Okio;
11+
import okio.Source;
12+
13+
/**
14+
* TODO: add description
15+
*/
16+
17+
public class UploadProgressResponse extends ResponseBody {
18+
private final ResponseBody responseBody;
19+
private final ProgressListener progressListener;
20+
private BufferedSource bufferedSource;
21+
private int mNotificationId;
22+
23+
public UploadProgressResponse(ResponseBody responseBody, ProgressListener progressListener,
24+
int notificationId) {
25+
this.responseBody = responseBody;
26+
this.progressListener = progressListener;
27+
this.mNotificationId = notificationId;
28+
}
29+
30+
@Override
31+
public MediaType contentType() {
32+
return responseBody.contentType();
33+
}
34+
35+
@Override
36+
public long contentLength() {
37+
return responseBody.contentLength();
38+
}
39+
40+
@Override
41+
public BufferedSource source() {
42+
if (bufferedSource == null) {
43+
bufferedSource = Okio.buffer(source(responseBody.source()));
44+
}
45+
return bufferedSource;
46+
}
47+
48+
private Source source(Source source) {
49+
return new ForwardingSource(source) {
50+
long totalBytesRead = 0L;
51+
52+
@Override
53+
public long read(Buffer sink, long byteCount) throws IOException {
54+
long bytesRead = super.read(sink, byteCount);
55+
// read() returns the number of bytes read, or -1 if this source is exhausted.
56+
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
57+
progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1, mNotificationId);
58+
return bytesRead;
59+
}
60+
};
61+
}
62+
63+
public interface ProgressListener {
64+
void update(long bytesRead, long contentLength, boolean done, int notificationId);
65+
}
66+
}

0 commit comments

Comments
 (0)