Issue
In my Android app I have up to 4 asynchronous tasks that depend on each other, which means that one task has to finish before the next one can go one with the retreived data. Now this can be quite unclear at some point when the code looks something like this:
final AsyncTask<Void, Void, Boolean> taskOne = new AsyncTask<Void, Void, Boolean>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... params) {
// retrieve required data
return true;
}
@Override
protected void onPostExecute(Boolean success) {
if (success) {
// start second task here
final AsyncTask<Void, Void, Boolean> taskTwo = new AsyncTask<Void, Void, Boolean>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... params) {
// retrieve required data
return true;
}
protected void onPostExecute(Boolean success) {
if (success) {
// start third task here
final AsyncTask<Void, Void, Boolean> taskThree = new AsyncTask<Void, Void, Boolean>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... params) {
// retrieve required data
return true;
}
protected void onPostExecute(Boolean success) {
if (success) {
// and so on ...
}
}
}
taskThree.execute();
}
}
}
taskTwo.execute();
}
}
}
taskOne.execute();
What would be the best practice to achieve this behaviour with a more readable code?
Thanks in advance
Solution
TaskOne
Class TaskOne extends AsyncTask{
onPostExecute(boolean success){
if(success){
new TaskTwo().execute();
}
}
}
TaskTwo
Class TaskTwo extends AsyncTask{
onPostExecute(boolean success){
if(success){
new TaskThree().execute();
}
}
}
TaskThree
Class TaskThree extends AsyncTask{
onPostExecute(boolean success){
if(success){
//do something
}
}
}
Answered By - Rajan Kali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.