suku suku - 1 month ago 7
Android Question

Volley RetryPolicy querying twice before timeout time is reached

I have set a retry policy for volley. The query is being sent twice despite the the timeout period not being reached.

StringRequest stringRequest = new StringRequest(method, currentURL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
S.L("response: " + currentURL);
listener.onRequestExecuted("response", response, downloadId);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("CCC", "Error " + error.toString());
}
})


This was the retry policy earlier

stringRequest.setRetryPolicy(new RetryPolicy() {
@Override
public int getCurrentTimeout() {
return 8000;
}

@Override
public int getCurrentRetryCount() {
return 1;
}

@Override
public void retry(VolleyError error) throws VolleyError {
S.L("Retry error: " + error);
}
});


On SO there was another question pertaining to this. It appears to do so when volley detects a slow connection despite timeout period is not reached. Here the solution was to use a different retry policy:

stringRequest.setRetryPolicy(new DefaultRetryPolicy(8000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


This worked and is sending only a single query in the timeout period

Why is there a difference in behaviour between the retry policies?

Answer

Why is there a difference in behaviour between the retry policies?

Because of the different retry() implementations.

From the source code of DefaultRetryPolicy:

@Override
public void retry(VolleyError error) throws VolleyError {
    mCurrentRetryCount++;
    mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier);
    if (!hasAttemptRemaining()) {
        throw error;
    }
}

protected boolean hasAttemptRemaining() {
    return mCurrentRetryCount <= mMaxNumRetries;
}

By passing DefaultRetryPolicy.DEFAULT_MAX_RETRIES to the constructor, you're effectively setting mMaxNumRetries to 1.

On the second retry hasAttemptRemaining() will return false and the VolleyError will be thrown.

Comments