Skip to content

Instantly share code, notes, and snippets.

@m7mdra
Forked from RyanRamchandar/Example.java
Created June 3, 2017 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m7mdra/178323878875baad34a26249775ce8d3 to your computer and use it in GitHub Desktop.
Save m7mdra/178323878875baad34a26249775ce8d3 to your computer and use it in GitHub Desktop.
Cancel a running or queued Call with OkHttp3
// ...
Request request = new Request.Builder()
.url(url)
.tag(TAG)
.build();
// Cancel previous call(s) if they are running or queued
OkHttpUtils.cancelCallWithTag(client, TAG);
// New call
Response response = client.newCall(request).execute();
// ...
package com.package.utils;
import com.package.utils.OkHttpUtils;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static org.junit.Assert.fail;
public class OkHttpProviderTest {
public final static String TAG = "tag";
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
private final OkHttpClient client = new OkHttpClient();
@Test
public void cancelRequestWithTag() throws Exception {
Request request = new Request.Builder()
.url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
.tag(TAG)
.build();
final long startNanos = System.nanoTime();
// Schedule a job to cancel the call in 1 second.
executor.schedule(new Runnable() {
@Override public void run() {
System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
OkHttpUtils.cancelCallWithTag(client, TAG);
System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
}
}, 1, TimeUnit.SECONDS);
try {
System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
Response response = client.newCall(request).execute(); // Synchronous
System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
(System.nanoTime() - startNanos) / 1e9f, response);
fail();
} catch (IOException e) {
System.out.printf("%.2f Call failed as expected: %s%n",
(System.nanoTime() - startNanos) / 1e9f, e);
}
}
}
package com.package.utils;
import okhttp3.Call;
import okhttp3.OkHttpClient;
public class OkHttpUtils {
public static void cancelCallWithTag(OkHttpClient client, String tag) {
for(Call call : client.dispatcher().queuedCalls()) {
if(call.request().tag().equals(tag))
call.cancel();
}
for(Call call : client.dispatcher().runningCalls()) {
if(call.request().tag().equals(tag))
call.cancel();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment