Avoid Multiple Requests When Using Volley
Many developers using Volley must have faced the problem of request being hit twice to the server. And as a result, they might get their request listener being delivered more than once. In many cases, this can mess-up your code’s logic.
The same happened to me when i was trying to make a delete request and updating the UI by deleting that item from the screen. But since, the delete request was hitting twice, i got two response listener one delivering success and other stating that no such item exist. This messed-up my app’s UI as the item got deleted from the screen and at the same time a toast appears on the screenÂ saying “Unable to delete!”.
I checked the logic which seems absolutely fine as i was making only one request. Also, when i checked the logs i saw the request was printed once and the response was delivered twice. This is when i realized that Volley must be making multiple requests to the server. But was still confused about how and why it must be doing that!
After googling and going through stackoverflow, i came to know that every request in Volley uses a default retry policy.
What is the default retry policy used by Volley??
Volley uses the following default policy:
/** The default socket timeout in milliseconds */
public static final int DEFAULT_TIMEOUT_MS = 2500;
/** The default number of retries */
public static final int DEFAULT_MAX_RETRIES = 0;
/** The default backoff multiplier */
public static final float DEFAULT_BACKOFF_MULT = 1f;
You can find these setting in DefaultRetryPolicy.java. So according to this default policy, Volley tries to wait for the response for 2500 milliseconds, however if the response is not received in this time span then it retries for the number set by the DEFAULT_MAX_RETRIES, i.e., 1. And the DEFAULT_BACKOFF_MULT variable is used to determine exponential time set to socket for every retry attempt. To understand it more deeply, you may refer Retry Policy.
How to configure Volley to stop sending two request to the server?
Now, to stop the multiple request you can configure retry policy for your request object by using the setRetryPolicy() method of the request object. I managed to do this with following code:
req.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0,
With the above code, i reduced the timeout to 20 seconds and set the number of retries to 0.
If above setting dose not work for you, then you may like to revisit your volley caching logic. Because of the soft ttl in volley caching the result gets delivered from the cache and at the same time it queues another network request which also will return a result. And therefore, single request but two different results.