'Cancel multiple Retrofit API calls at once

Past few days I am searching for a Retrofit2 feature. Is there any option or way to cancel multiple API calls at once, requested from a client?

For example, I have to call 5 APIs in a sequence, and while the app calls those 5 APIs, the user can do other actions in the app. In case, if the user has called another API, I have to prioritize the last called API and hold or terminate the previous 5 API calls. Right now what happens is, that the user called API will be in the queue till the previous APIs completes.

I have found that Retrofit2 has a method called 'cancel()', but it works only for one API, not working for multiple API calls.

I am using retrofit - 2.9.0

Here is my API Client class,

public class ApiClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(Context context) {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
                .callTimeout(4, TimeUnit.MINUTES)
                .connectTimeout(4, TimeUnit.MINUTES)
                .readTimeout(4, TimeUnit.MINUTES)
                .writeTimeout(4, TimeUnit.MINUTES);

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl("BASE-URL")
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build())
                    .build();
        }
        return retrofit;
    }
}

Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source