I have two asyc task both perform separate network operation.I want one async task to wait for other task to finish for a single variable..I thought of doing it like perform other asyc operation onPostexecute of first one but for a single variable i have to make other task to wait first one to finish...is there any to achieve efficently
You will need to call AsyncTask. get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.
This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.
To wait for a coroutine to finish, you can call Job. join . join is a suspending function, meaning that the coroutine calling it will be suspended until it is told to resume. At the point of suspension, the executing thread is released to any other available coroutines (that are sharing that thread or thread pool).
Referring to this, you can not use .execute() so;
First you have to start your tasks like this:
// Start first task
new Task1().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
// Start second task
new Task2().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
and then you can make a static variable so the both of tasks can access to it:
public static boolean task1Finished = false;
Then simple example of the tasks:
First task
private class Task1 extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
Log.d("myApp", "Task1 started");
for(int x = 0; x < 10; ++x)
{
try
{
Thread.sleep(1000);
//Log.d("myApp", "sleeped 1000 ms");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
return "";
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(String result) {
// Lets the second task to know that first has finished
task1Finished = true;
}
}
Second task
private class Task2 extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
Log.d("myApp", "Task2 started");
while( task1Finished == false )
{
try
{
Log.d("myApp", "Waiting for Task1");
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
Log.d("myApp", "Task1 finished");
// Do what ever you like
// ...
return "";
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(String result) {
Log.d("myApp", "All done here (Task2)");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With