Carlos Hernández Gil Carlos Hernández Gil - 1 year ago 349
Android Question

Execute http request in parallel with Retrofit 2

I want to implement multiple parallel request in Retrofit 2.
I have the following structure to make 3 request :

HistoricalRApi.IStockChart service=HistoricalRApi.getMyApiService();
Call<HistoricalDataResponseTimestamp> call1= service.get1DHistoricalDataByStock("^IXIC");
Call<HistoricalDataResponseTimestamp> call2= service.get1DHistoricalDataByStock("^DJI");
Call<HistoricalDataResponseTimestamp> call3= service.get1DHistoricalDataByStock("^GSPC");

I have read that in Retrofit1, when defining the rest adapter one can define parallel request with .setExecutor like here:

RestAdapter adapter = new RestAdapter.Builder()
.setExecutors(Executors.newFixedThreadPool(3), null)

My question is how can i achieve the same in Retrofit 2? Thanks in advance

Answer Source

Thanks to Colin Gillespie link i have implemented what Jake Wharton says and this is the result:

 public static IStockChart getMyApiService() {
        OkHttpClient client=new OkHttpClient();
        Dispatcher dispatcher=new Dispatcher();
       // OkHttpClient client = new OkHttpClient();
       //  HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
       //  interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
       //  client.interceptors().add(interceptor);
        if(myService ==null){
            Retrofit retrofit=new Retrofit.Builder()
            return myService;
        } else {
            return myService;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download