Skip to content

Commit

Permalink
Use Android's default network throttling algorithm when streaming res…
Browse files Browse the repository at this point in the history
…ponses (or flush when chunks crest 8K).

Reviewed By: lexs

Differential Revision: D3157879

fb-gh-sync-id: ab5fe320288af01fc789ba26db6fd3b7c58fb31d
fbshipit-source-id: ab5fe320288af01fc789ba26db6fd3b7c58fb31d
  • Loading branch information
steveluscher authored and Facebook Github Bot 9 committed Apr 11, 2016
1 parent c24fae9 commit c18210b
Showing 1 changed file with 3 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,7 @@ public final class NetworkingModule extends ReactContextBaseJavaModule {
private static final String REQUEST_BODY_KEY_FORMDATA = "formData";
private static final String USER_AGENT_HEADER_NAME = "user-agent";

private static final int MIN_BUFFER_SIZE = 8 * 1024; // 8kb
private static final int MAX_BUFFER_SIZE = 512 * 1024; // 512kb

private static final int CHUNK_TIMEOUT_NS = 100 * 1000000; // 100ms
private static final int MAX_CHUNK_SIZE_BETWEEN_FLUSHES = 8 * 1024; // 8K

private final OkHttpClient mClient;
private final ForwardingCookieHandler mCookieHandler;
Expand Down Expand Up @@ -279,41 +276,16 @@ private void readWithProgress(
ResponseBody responseBody) throws IOException {
Reader reader = responseBody.charStream();
try {
StringBuilder sb = new StringBuilder(getBufferSize(responseBody));
char[] buffer = new char[MIN_BUFFER_SIZE];
char[] buffer = new char[MAX_CHUNK_SIZE_BETWEEN_FLUSHES];
int read;
long last = System.nanoTime();
while ((read = reader.read(buffer)) != -1) {
sb.append(buffer, 0, read);
long now = System.nanoTime();
if (shouldDispatch(now, last)) {
onDataReceived(executorToken, requestId, sb.toString());
sb.setLength(0);
last = now;
}
}

if (sb.length() > 0) {
onDataReceived(executorToken, requestId, sb.toString());
onDataReceived(executorToken, requestId, new String(buffer, 0, read));
}
} finally {
reader.close();
}
}

private static boolean shouldDispatch(long now, long last) {
return last + CHUNK_TIMEOUT_NS < now;
}

private static int getBufferSize(ResponseBody responseBody) throws IOException {
long length = responseBody.contentLength();
if (length == -1) {
return MIN_BUFFER_SIZE;
} else {
return (int) min(length, MAX_BUFFER_SIZE);
}
}

private void onDataReceived(ExecutorToken ExecutorToken, int requestId, String data) {
WritableArray args = Arguments.createArray();
args.pushInt(requestId);
Expand Down

0 comments on commit c18210b

Please sign in to comment.