我想在Retrofit 2中实现多个并行请求。 我有以下结构来提出3个请求:
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());
}
我已经在Retrofit1中看到,在定义其余适配器时,可以使用.setExecutor定义并行请求,如下所示:
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(END_POINT)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setExecutors(Executors.newFixedThreadPool(3), null)
.build();
我的问题是如何在Retrofit 2中实现同样的目标?提前致谢
答案 0 :(得分:17)
感谢Colin Gillespie链接我实施了Jake Wharton所说的结果:
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;
}
}