Skip to content

Instantly share code, notes, and snippets.

@RyanRamchandar
Last active November 9, 2022 17:27
Show Gist options
  • Save RyanRamchandar/64c5863838940ec67f03 to your computer and use it in GitHub Desktop.
Save RyanRamchandar/64c5863838940ec67f03 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();
}
}
}
@ngheungyu
Copy link

Thanks for the example. How about calling client.dispatcher().cancelAll() directly?

@vanshg
Copy link

vanshg commented Aug 25, 2016

@ngheungyu: You wouldn't want to call cancelAll() if you want to only delete requests with a certain tag

@hunter-t
Copy link

Thank you for sharing this example!

@complexfly
Copy link

thank you!

@Duna
Copy link

Duna commented Aug 9, 2019

For better handling of NPE we suggest to put the tag first when string comparison

public class OkHttpUtils {
    public static void cancelCallWithTag(OkHttpClient client, String tag) {
        for(Call call : client.dispatcher().queuedCalls()) {
            if(tag.equals(call.request().tag()))
                call.cancel();
        }
        for(Call call : client.dispatcher().runningCalls()) {
            if(tag.equals(call.request().tag()))
                call.cancel();
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment