10

I'm looking for a best practice for making concurrent network requests using the OKHTTP library.

Basically here's what I want to do:

I want to write a method that makes N concurrent network requests to different URLs, and return ONLY when ALL N requests have returned.

I thought about manually writing Threads and Runnables and such to create a group of request pool, but was wondering if there's some sort of easier way to do this. So my question is:

  1. Does OKHTTP support concurrent request API natively somehow?
  2. If not, what's the best way to implement this?
Vlad
  • 8,038
  • 14
  • 60
  • 92
  • 2
    RxJava around OkHttp could help you – OneCricketeer Jan 24 '17 at 16:29
  • you can use `countDownLatch` either, initialize that with N and use `await` in non UI thread because this will be block your thread, then in oSuccess of each request call `countDown`, after `await` do what you want. – Shayan Pourvatan Jan 24 '17 at 17:02

1 Answers1

17

OkHttp natively supports asynchronous requests efficiently e.g. sharing the optimum number of connections.

See https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.java

For the second part of the question, you use a CountdownLatch or you can bridge to java Futures like the following

public class OkHttpResponseFuture implements Callback {
  public final CompletableFuture<Response> future = new CompletableFuture<>();

  public OkHttpResponseFuture() {
  }

  @Override public void onFailure(Call call, IOException e) {
    future.completeExceptionally(e);
  }

  @Override public void onResponse(Call call, Response response) throws IOException {
    future.complete(response);
  }
}

And call

  private Future<Response> makeRequest(OkHttpClient client, Request request) {
    Call call = client.newCall(request);

    OkHttpResponseFuture result = new OkHttpResponseFuture();

    call.enqueue(result);

    return result.future;
  }

At that point you can use methods like CompletableFuture.allOf

n.b. if you wrap with Futures, it can be easy to not close the Response objects when one fails.

Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69