Skip to content

Commit 8b1243c

Browse files
committed
Allow assign TAGs to RequestHandles and cancel requests that contain specific TAG
1 parent 908e251 commit 8b1243c

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

library/src/main/java/com/loopj/android/http/AsyncHttpClient.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
import android.content.Context;
2222
import android.os.Looper;
23-
import android.util.Log;
2423

2524
import org.apache.http.Header;
2625
import org.apache.http.HeaderElement;
@@ -829,6 +828,30 @@ public void cancelAllRequests(boolean mayInterruptIfRunning) {
829828
requestMap.clear();
830829
}
831830

831+
/**
832+
* Allows you to cancel all requests currently in queue or running, by set TAG,
833+
* if passed TAG is null, will not attempt to cancel any requests, if TAG is null
834+
* on RequestHandle, it cannot be canceled by this call
835+
*
836+
* @param TAG TAG to be matched in RequestHandle
837+
* @param mayInterruptIfRunning specifies if active requests should be cancelled along with
838+
* pending requests.
839+
*/
840+
public void cancelRequestsByTAG(Object TAG, boolean mayInterruptIfRunning) {
841+
if (TAG == null) {
842+
log.d(LOG_TAG, "cancelRequestsByTAG, passed TAG is null, cannot proceed");
843+
return;
844+
}
845+
for (List<RequestHandle> requestList : requestMap.values()) {
846+
if (requestList != null) {
847+
for (RequestHandle requestHandle : requestList) {
848+
if (TAG.equals(requestHandle.getTag()))
849+
requestHandle.cancel(mayInterruptIfRunning);
850+
}
851+
}
852+
}
853+
}
854+
832855
// [+] HTTP HEAD
833856

834857
/**

library/src/main/java/com/loopj/android/http/RequestHandle.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
*/
2828
public class RequestHandle {
2929
private final WeakReference<AsyncHttpRequest> request;
30+
private WeakReference<Object> TAG = null;
3031

3132
public RequestHandle(AsyncHttpRequest request) {
3233
this.request = new WeakReference<AsyncHttpRequest>(request);
@@ -95,4 +96,23 @@ public boolean shouldBeGarbageCollected() {
9596
request.clear();
9697
return should;
9798
}
99+
100+
/**
101+
* Will set Object as TAG to this request, wrapped by WeakReference
102+
*
103+
* @param tag Object used as TAG to this RequestHandle
104+
*/
105+
public RequestHandle setTag(Object tag) {
106+
TAG = new WeakReference<Object>(tag);
107+
return this;
108+
}
109+
110+
/**
111+
* Will return TAG of this RequestHandle
112+
*
113+
* @return Object TAG, can be null
114+
*/
115+
public Object getTag() {
116+
return TAG.get();
117+
}
98118
}

0 commit comments

Comments
 (0)