Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel HTTP requests with Retrofit

Tags:

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?

like image 522
Vektor88 Avatar asked Apr 23 '14 21:04

Vektor88


People also ask

What is retrofit HTTP client?

Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp.

Is retrofit a REST API?

Retrofit is type-safe REST client for Android and Java which aims to make it easier to consume RESTful web services.

How do you call parallel in Java?

So you want to parallelize these two independent calls. To do so, you have to do the following steps : Add @Async annotation to the function you want to parallelize getCountriesByLanguage and getCountriesByRegion. Change the return type of the function by CompletableFuture<List<Country>>


1 Answers

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.

like image 180
Jake Wharton Avatar answered Sep 18 '22 15:09

Jake Wharton