15

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

HistoricalRApi.IStockChart service=HistoricalRApi.getMyApiService();
        //^BVSP,^DJI,^IXIC
        Call<HistoricalDataResponseTimestamp> call1= service.get1DHistoricalDataByStock("^IXIC");
        Call<HistoricalDataResponseTimestamp> call2= service.get1DHistoricalDataByStock("^DJI");
        Call<HistoricalDataResponseTimestamp> call3= service.get1DHistoricalDataByStock("^GSPC");
        call1.enqueue(retrofitCallbackAmerica());
        call2.enqueue(retrofitCallbackAmerica());
        call3.enqueue(retrofitCallbackAmerica());
}

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()
                .setEndpoint(END_POINT) 
                .setLogLevel(RestAdapter.LogLevel.FULL) 
                .setExecutors(Executors.newFixedThreadPool(3), null)
                .build(); 

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

Carlos Hernández Gil
  • 1,853
  • 2
  • 22
  • 30

1 Answers1

21

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();
        dispatcher.setMaxRequests(3);
        client.setDispatcher(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()
                    .baseUrl("http://chartapi.finance.yahoo.com/")
                    .addConverterFactory(JsonpGsonConverterFactory.create())
                    .client(client)
                    .build();
            myService=retrofit.create(IStockChart.class);
            return myService;
        } else {
            return myService;
        }



    }
Carlos Hernández Gil
  • 1,853
  • 2
  • 22
  • 30
  • 1
    You can even get the dispatcher and cancel all requests (pending and executing) if the user leaves the app or actvity and save resources. Because the pending requests will complete anyway. dispatcher.cancelAll() – Sergio Jun 02 '19 at 22:45