Parallel HTTP requests with Retrofit

2020-02-08 08:17发布

问题:

I have an Android application that is currently using Volley library to make network requests and show downloaded images with NetworkImageView.

I would like to test Retrofit's capabilities and since I need to run lots of requests (thousands) I'm a bit concerned about the parallel execution. Volley handles parallel requests with the RequestQueue that limits the concurrent running requests to four, while the other requests are enqueued waiting to be executed. In Retrofit documentations I haven't found any way to handle the number of concurrent requests and I suspect that such details are left to the developer in this library.

Is this correct? If so, is there any android-oriented implementation/library available? Otherwise, what are the best practices to handle parallel requests?

回答1:

Retrofit uses an Executor for queueing requests.

The default uses Executors.newCachedThreadPool which allows for unlimited threads. This fits most use cases since normally you would only ever have one or two requests happening at once.

You can change this behavior, however, by supplying your own when building the RestAdapter. Call setExecutors and pass in an executor that uses a confined thread pool (limited to whatever number you would like). For the second argument, simply pass a new instance of MainThreadExecutor so that callbacks happen on the main thread.