title: Correct way to communicate the result of a background thread to the Ui Thread in Android
body: <p>This is one of the most confusing topics for me. <strong>So my question is, what is the <em>correct way</em> of communicate the result of background thread when this finish?</strong>.</p>
  <p>Imagine I want to update some <code>TextView</code> with some information I just downloaded.There is 3 things I use when I need to perform background tasks:</p>
  <h2>AsyncTask</h2>
  <p>Very easy to use, this one has the <code>onPostExecute()</code> method that will return the result directly to the UiThread so I can use a callback interface or do whatever I want. I liked this class but it's <strong>deprecated.</strong></p>
  <h2>ThreadPoolExecutor</h2>
  <p>This is what I actually use when need to perform background tasks and here comes my problem, the moment when I have to give the result to the UiThread. I have informed myself about <code>Looper</code> and <code>Handler</code> classes and about the <code>mainLooper</code>.</p>
  <p>So, when I need to return some results I use the method <code>runOnUiThread()</code> that, as I have readed, just get the <code>Looper</code> of the Ui thread and post my <code>Runnable</code> to the queue.</p>
  <p>Well this is working and I can communicate with the main thread but, I find it really ugly, and I am sure there is a more elegant way of doing it than populate all my code of &quot;<code>runOnUiThread()</code>&quot; methods. Also, if the background task need too much time, maybe the user already change of <code>Activity</code> or <code>Fragment</code> when the code inside <code>runOnUiThread()</code> runs what will cause <code>Exceptions</code> (I know using <code>LiveData</code> and <code>MVVM</code> pattern would solve this last problem but I am working in a legacy project and I can't refactor all the code so I am working with the clasical Activity mvc pattern)</p>
  <p><strong>So, there is another way of doing this? Could you give an example?</strong> I really searched a lot but didn't find anything...</p>
  <h2>Coroutines</h2>
  <p>I am actually working in a legacy project and I must use Java so can't use Kotlin <code>coroutines</code>, but I find them easy to use and so powerfull.</p>
  <p>Any help would be appreciated!</p>