Skip to content

Instantly share code, notes, and snippets.

@newbyca
Created May 9, 2012 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save newbyca/2640579 to your computer and use it in GitHub Desktop.
Save newbyca/2640579 to your computer and use it in GitHub Desktop.
Android ListenableAsyncTask: AsyncTask extension that lets you set an onPostExecute listener from a task's client
public abstract class ListenableAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result>{
@Override
protected final void onPostExecute(Result result) {
notifyListenerOnPostExecute(result);
}
private AsyncTaskListener<Result> mListener;
public interface AsyncTaskListener<Result>{
public void onPostExecute(Result result);
}
public void listenWith(AsyncTaskListener<Result> l){
mListener = l;
}
private void notifyListenerOnPostExecute(Result result){
if(mListener != null)
mListener.onPostExecute(result);
}
}
@newbyca
Copy link
Author

newbyca commented May 9, 2012

I kept coming to this point where it felt more natural to set a listener for onPostExecute from a given task instance's client context. So I tried this abstract extension class and it worked quite swell. Just derive your concrete task class from ListenableAsyncTask instead of the SDK's AsyncTask. Everything else works the same as AsyncTask with the added feature that you can now be notified about onPostExecute from outside the task instance.

@nvictor
Copy link

nvictor commented Mar 3, 2014

hey,

i think you solved my problem : ) AsyncTask's by nature aren't meant to be singletons. They can't outlive their listeners. from what you have written, it seems clear that the listener can be re-bound at any point between doInBackground() and onPostExecute(). i will try this tonight.

thanks.

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