title: Android AsyncTask - Changing listeners
body: <p>I have an <code>AsyncTask</code> which never dies. The listener to the events in this <code>AsyncTask</code> keeps changing(depending on which activity/fragment is visible to the user). To accomplish this, I have a setup like the following :</p>
  
  <ul>
  <li>An interface :</li>
  </ul>
  
  <blockquote>
  <pre><code>public interface TaskListener {
     public void onItemChanged(String itemName)
  }
  </code></pre>
  </blockquote>
  
  <ul>
  <li>AsyncTask which contains a <code>TaskListener</code> Member variable which is registered/unregistered using public methods.</li>
  </ul>
  
  <blockquote>
  <pre><code>public void registerListener(TaskListener listener) {
      mListener = listener;
  }
  
  public void unregisterListener() {
      mListener = null;
  }
  </code></pre>
  </blockquote>
  
  <ul>
  <li>In the <code>onPublishProgress()</code> method (called via <code>publishProgress()</code> in the <code>doInBackground()</code> method) of the <code>AsyncTask</code>, I notify the listener.</li>
  </ul>
  
  <p>Now, my question is are there any caveats for this situation while notifying the listener? In particular, I would like to know whether it is thread safe or not. i.e., if <code>publishProgress()</code> and <code>registerListener()</code> is called at the same time, will the right listener receives a callback?</p>