Skip to content

Commit

Permalink
Small refactors in HttpHandler
Browse files Browse the repository at this point in the history
 - Delegate default constructor
 - Compare URL string instead of 'tag' for cancellation
 - onCancel cancels all calls with the given URL, in case more than one does
  • Loading branch information
matteblair committed Dec 22, 2016
1 parent 7cf5eb8 commit 3c16542
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,10 @@ public void run() {

HttpHandler getHttpHandler() {
File cacheDir = getExternalCacheDir();
HttpHandler handler;
if (cacheDir != null && cacheDir.exists()) {
handler = new HttpHandler(new File(cacheDir, "tile_cache"), 30 * 1024 * 1024);
} else {
handler = new HttpHandler();
return new HttpHandler(new File(cacheDir, "tile_cache"), 30 * 1024 * 1024);
}

return handler;
return new HttpHandler();
}

@Override
Expand Down
26 changes: 11 additions & 15 deletions android/tangram/src/main/java/com/mapzen/tangram/HttpHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,7 @@ public class HttpHandler {
* Construct an {@code HttpHandler} with default options.
*/
public HttpHandler() {
okClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
this(null, 0);
}

/**
Expand All @@ -36,13 +32,16 @@ public HttpHandler() {
* @param maxSize Maximum size of data to cache, in bytes
*/
public HttpHandler(File directory, long maxSize) {
Cache okTileCache = new Cache(directory, maxSize);
okClient = new OkHttpClient.Builder()
.cache(okTileCache)
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
.readTimeout(30, TimeUnit.SECONDS);

if (directory != null && maxSize > 0) {
builder.cache(new Cache(directory, maxSize));
}

okClient = builder.build();
}

/**
Expand All @@ -53,7 +52,6 @@ public HttpHandler(File directory, long maxSize) {
*/
public boolean onRequest(String url, Callback cb) {
Request request = new Request.Builder()
.tag(url)
.url(url)
.build();
okClient.newCall(request).enqueue(cb);
Expand All @@ -68,17 +66,15 @@ public void onCancel(String url) {

// check and cancel running call
for (Call runningCall : okClient.dispatcher().runningCalls()) {
if (runningCall.request().tag().equals(url)) {
if (runningCall.request().url().toString().equals(url)) {
runningCall.cancel();
return;
}
}

// check and cancel queued call
for (Call queuedCall : okClient.dispatcher().queuedCalls()) {
if (queuedCall.request().tag().equals(url)) {
if (queuedCall.request().url().toString().equals(url)) {
queuedCall.cancel();
return;
}
}
}
Expand Down

0 comments on commit 3c16542

Please sign in to comment.