Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        //^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

like image 422
Carlos Hernández Gil Avatar asked Jan 26 '16 10:01

Carlos Hernández Gil


1 Answers

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;
        }



    }
like image 95
Carlos Hernández Gil Avatar answered Nov 02 '22 14:11

Carlos Hernández Gil