2016-08-03 44 views
1

我讓應用程序使用youtube API。首先我使用Retrofit加載列表視頻,然後我繼續使用Retrofit加載列表中的所有視頻信息。通過改進2取消所有請求

因爲listview支持刷新和加載更多我需要cancel所有請求召回。

我知道致電cancel()函數取消請求。我可以取消所有請求,將所有撥打電話到一個堆棧和調用cancel()每個撥打

有沒有更好的解決方案?

+0

[http://stackoverflow.com只需調用/questions/34367910/retrofit-2-okhttp-cancel-all-running-requests](http://stackoverflow.com/questions/343679 10/retrofit-2-okhttp-cancel-all-running-requests) –

+0

我讀了這個主題。但我不知道'retrofit.client()。cancel(...)',找不到函數。 – phongvan

+0

在那個線程已經說過使用'dispatcher'爲此becoz我檢查'dispatcher'有'cancelAll();'方法 –

回答

3

假設我有

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(); 

現在用Dispatcher創建服務,並設置爲Retrofit

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

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

,並從任何地方

dispatcher.cancelAll(); 
+0

調度器如何取消已發佈的請求,並且會執行回調。由於我使用調度員onStop()取消請求,但正在運行的請求。但在慢速網絡上。發佈的請求仍被稱爲回調並導致一些異常。 – Killer