Guest User

Retrofit2 CancelableCallback

a guest
Jan 6th, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. public abstract class CancelableCallback<T> implements Callback<T> {
  2.  
  3.     private static List<CancelableCallback> mList = new ArrayList<>();
  4.  
  5.     private boolean isCanceled = false;
  6.     private Object mTag = null;
  7.  
  8.     public static void cancelAll() {
  9.         Iterator<CancelableCallback> iterator = mList.iterator();
  10.         while (iterator.hasNext()){
  11.             iterator.next().isCanceled = true;
  12.             iterator.remove();
  13.         }
  14.     }
  15.  
  16.     public static void cancel(Object tag) {
  17.         if (tag != null) {
  18.             Iterator<CancelableCallback> iterator = mList.iterator();
  19.             CancelableCallback item;
  20.             while (iterator.hasNext()) {
  21.                 item = iterator.next();
  22.                 if (tag.equals(item.mTag)) {
  23.                     item.isCanceled = true;
  24.                     iterator.remove();
  25.                 }
  26.             }
  27.         }
  28.     }
  29.  
  30.     public CancelableCallback() {
  31.         mList.add(this);
  32.     }
  33.  
  34.     public CancelableCallback(Object tag) {
  35.         mTag = tag;
  36.         mList.add(this);
  37.     }
  38.  
  39.     public void cancel() {
  40.         isCanceled = true;
  41.         mList.remove(this);
  42.     }
  43.  
  44.     @Override
  45.     public void onResponse(Call<T> call, Response<T> response) {
  46.         if (!isCanceled) {
  47.             onSuccess(call, response);
  48.         }
  49.         mList.remove(this);
  50.     }
  51.  
  52.     @Override
  53.     public void onFailure(Call<T> call, Throwable t) {
  54.         if (!isCanceled) {
  55.             onError(call, t);
  56.         }
  57.     }
  58.  
  59.     public abstract void onSuccess(Call<T> call, Response<T> response);
  60.     public abstract void onError(Call<T> call, Throwable t);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment