前言
在某一个界面,用戶發起了一個網絡請求,由於某種緣由用戶在網絡請求完成前離開了當前界面,比較好的作法是取消這個網絡請求。對於OkHttp來講,具體是調用Call的cancel方法。
如何找到這一個網絡請求並取消掉它呢?
操做大體分爲3步。第一步,在創建請求時,給請求(request)添加標記;第二步,根據標記,找到請求;最後,取消這個請求。
OkHttp中的tag
要取消一個請求,OkHttp中能夠使用cancel方法
OkHttp的request對象有tag。能夠根據tag來標示請求。
//Set tags for your requests when you build them:
Request request = new Request.Builder().
url(url).tag("requestKey").build();
//When you want to cancel:
//A) go through the queued calls and cancel if the tag matches:
for (Call call : mHttpClient.dispatcher().queuedCalls()) {
if (call.request().tag().equals("requestKey"))
call.cancel();
}
//B) go through the running calls and cancel if the tag matches:
for (Call call