2016-01-26 9 views
11

voglio implementare più richiesta parallelo nel retrofit 2. Ho la seguente struttura a fare 3 Richiesta:eseguire la richiesta http in parallelo con Retrofit 2

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

Ho letto che in Retrofit1, al momento di definire il adattatore resto si può definire richiesta parallelo con .setExecutor come qui:

RestAdapter adapter = new RestAdapter.Builder() 
       .setEndpoint(END_POINT) 
       .setLogLevel(RestAdapter.LogLevel.FULL) 
       .setExecutors(Executors.newFixedThreadPool(3), null) 
       .build(); 

la mia domanda è come posso ottenere lo stesso in Retrofit 2? Grazie in anticipo

+2

https://github.com/square/retrofit/issues/1259 – Breavyn

risposta

13

Grazie al collegamento Colin Gillespie ho implementato ciò che Jake Wharton dice e questo è il risultato:

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



    }