Created
May 9, 2012 00:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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
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.