mdtuyen
mdtuyen

Reputation: 4528

Cancel all request by retrofit2

I make an application use youtube API. The first I use Retrofit to load list video then I continue use Retrofit to load all information of Video in the list.

Because the listview support refresh and loadmore I need cancel all request to recall.

I know Call have cancel() function to cancel request. I can cancel all request by put all Call to a Stack and call cancel() for each Call.

Are there more better solution ?

Upvotes: 1

Views: 3474

Answers (1)

M D
M D

Reputation: 47807

Suppose i have

 HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);

 OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

 OkHttpClient client = httpClient.addInterceptor(interceptor).build();

 Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl("MY URL")
                .client(new OkHttpClient.Builder().addInterceptor(interceptor).build())
                .addConverterFactory(GsonConverterFactory.create());

 OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

Now create service with Dispatcher and set to Retrofit

 Dispatcher dispatcher=new Dispatcher();
 dispatcher.setMaxRequests(totalRequest);
 httpClient.dispatcher(dispatcher);

 Retrofit retrofit = builder.client(client).build();
 Service servicee = retrofit.create(serviceClass)

and just call from any where

dispatcher.cancelAll();

Upvotes: 5

Related Questions