javaandroidqueueandroid-volleyrequest-queueing

Preventing the same request from being sent simultaneously by Volley


I'm developing a general purpose library for Android apps and I'm using Volley to send requests over the network. 2 issues that came from the same problem: the user clicks the Button several times and the request is queued the # of times the user clicked the Button (which points to the same user XP problem).

I wish to tackle the problem on two issues in the client side of things:

How can I use Volley in order to not queue the same request twice?


Solution

  • How can I use Volley in order to not queue the same request twice?

    Volley has no methods to interact with its RequestQueue (other than add(), cancelAll() and finish()).

    You could use reflection to access the mCurrentRequests field (and compare your Request with the queued Requests), which i do not recommend.

    You could just add your queued requests to a WeakHashMap (with the Request as the key) and check your new requests for equality (based on your implementation) with the key set.

    For example:

    RequestQueue requestQueue;
    WeakHashMap<StringRequest, String> queuedRequests;
    
    // ...
    
    private boolean addRequestToQueue(StringRequest request, String tag) {
        for(StringRequest queuedRequest : queuedRequests.keySet()) {
            if(tag.equals(queuedRequest.getTag())) {
                return false;
            }
        }
    
        request.setTag(tag);
        requestQueue.add(request);
        queuedRequests.put(request, tag);
    
        return true;
    }