Perform requests with Retrofit inside custom Runnable

Vektor88 picture Vektor88 · Apr 24, 2014 · Viewed 10.2k times · Source

I am migrating from Volley to a custom implementation using Retrofit, but I'm trying to add to my implementation some of the Volley features that I liked, for example

RequestQueue.cancel(String tag)

If the Request has the requested tag, then it's canceled by setting a boolean value, mCanceled, to true. The run method checks this value and returns if it's true. To be able to reproduce this with Retrofit I should be able to use my custom class implementing Runnable instead of the default one, where I have a mTag and a mCanceled field. Moreover, Volley was also able to set such flag inside the active Threads and immediately stop them. My cancelAll method, that I've already implemented, just drains the queue to another queue, but isn't able to access the active threads. Is it possible to achieve the same results with Retrofit and ThreadPoolExecutor?

Answer

Vektor88 picture Vektor88 · Apr 24, 2014

I think I've found a nicer solution: instead of blocking the Runnable of the requests, I am blocking the Callback execution.

I have extended the Callback interface:

public interface CustomCallbackInterface<T> extends Callback<T> {
    public String getTag();
    public String setTag(String tag);
    public void cancel();
    public boolean isCanceled();
}

so that each Callback has a tag and a cancel flag. Then the success method starts with:

public class CustomCallback<ConvertedData> implements CustomCallbackInterface<ConvertedData>{

    //failure...

    @Override
    public void success(ConvertedData cd, Response response) {
        if(isCanceled()) return;
        // ....
    }
}

Every time I make a new request, I store the created CustomCallback inside a List cancel just iterates the list and calls cancel() on the items with the same tag.