Skip to content

Instantly share code, notes, and snippets.

@ThanosFisherman
Last active November 7, 2016 18:10
Show Gist options
  • Save ThanosFisherman/6d1e5ae65f737610d60ee8d0ce499fb2 to your computer and use it in GitHub Desktop.
Save ThanosFisherman/6d1e5ae65f737610d60ee8d0ce499fb2 to your computer and use it in GitHub Desktop.
Asynctask wrapped in a retained fragment
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
public abstract class RetainedAsyncTask<Params, Progress, Result> extends Fragment
{
private AsyncCustom asyncCustom;
public RetainedAsyncTask()
{
asyncCustom = new AsyncCustom();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@SuppressWarnings("unchecked")
public void execute(Params... params)
{
if (asyncCustom.getStatus() == AsyncTask.Status.FINISHED)
asyncCustom = new AsyncCustom();
asyncCustom.execute(params);
}
public void cancel(boolean mayInterrupt)
{
asyncCustom.cancel(mayInterrupt);
}
protected boolean isCancelled()
{
return asyncCustom.isCancelled();
}
protected abstract void onPostExecute(Result result);
protected abstract void onPreExecute();
@SuppressWarnings("unchecked")
protected abstract void onProgressUpdate(Progress... values);
protected abstract void onCancelled();
private final class AsyncCustom extends AsyncTask<Params, Progress, Result>
{
@SafeVarargs
@Override
protected final Result doInBackground(Params... paramses)
{
return RetainedAsyncTask.this.loadInBackground(paramses);
}
@Override
protected void onPostExecute(Result result)
{
RetainedAsyncTask.this.onPostExecute(result);
}
@Override
protected void onPreExecute()
{
RetainedAsyncTask.this.onPreExecute();
}
@SafeVarargs
@Override
protected final void onProgressUpdate(Progress... values)
{
RetainedAsyncTask.this.onProgressUpdate(values);
}
@Override
protected void onCancelled()
{
RetainedAsyncTask.this.onCancelled();
}
}
@SuppressWarnings("unchecked")
protected abstract Result loadInBackground(Params... paramses);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment