Skip to content

Instantly share code, notes, and snippets.

@dco5
Created February 1, 2017 19:26
Show Gist options
  • Save dco5/877ae18e7c1d84ba081c2bfe28cf2173 to your computer and use it in GitHub Desktop.
Save dco5/877ae18e7c1d84ba081c2bfe28cf2173 to your computer and use it in GitHub Desktop.
public abstract class RepeatableAsyncTask<A, B, C> extends AsyncTask<A, B, C> {
private static final String TAG = "RepeatableAsyncTask";
public static final int DEFAULT_MAX_RETRY = 5;
private int mMaxRetries = DEFAULT_MAX_RETRY;
private Exception mException = null;
/**
* Default constructor
*/
public RepeatableAsyncTask() {
super();
}
/**
* Constructs an AsyncTask that will repeate itself for max Retries
* @param retries Max Retries.
*/
public RepeatableAsyncTask(int retries) {
super();
mMaxRetries = retries;
}
/**
* Will be repeated for max retries while the result is null or an exception is thrown.
* @param inputs Same as AsyncTask's
* @return Same as AsyncTask's
*/
protected abstract C repeatInBackground(A...inputs);
@Override
protected final C doInBackground(A...inputs) {
int tries = 0;
C result = null;
/* This is the main loop, repeatInBackground will be repeated until result will not be null */
while(tries++ < mMaxRetries && result == null) {
try {
result = repeatInBackground(inputs);
} catch (Exception exception) {
/* You might want to log the exception everytime, do it here. */
mException = exception;
}
}
return result;
}
/**
* Like onPostExecute but will return an eventual Exception
* @param c Result same as AsyncTask
* @param exception Exception thrown in the loop, even if the result is not null.
*/
protected abstract void onPostExecute(C c, Exception exception);
@Override
protected final void onPostExecute(C c) {
super.onPostExecute(c);
onPostExecute(c, mException);
}
}
@dco5
Copy link
Author

dco5 commented Feb 1, 2017

Extend in place of AsyncTask, the only big difference is that you will use repeatInBackground instead of doInBackground and that onPostExecute will have a new parameter, the eventual Exception thrown.

Anything inside repeatInBackground will be repeated automatically until result is different from null / exception is not thrown and there are been less than maxTries.

The last exception thrown inside the loop will be returned in the onPostExecute(Result, Exception).

You can set max tries using the RepeatableAsyncTask(int retries) constructor.

http://stackoverflow.com/questions/18359039/repeat-asynctask

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment