5

I have to make several calls to a web service, but each step uses the values from the previous step, so right now I have a huge chain of AsyncTasks: each AsyncTask is executed in the onPostExecute() of the AsyncTask of the previous step. This is very very ugly, and very hard to modify. How can I avoid this? I would like to put each step in a separate function:

int step5() //this function is on the main UI thread
{
   return getStep5ValuesFromWebService() + valuesFromPreviousSteps;
}

int getStep5ValuesFromWebService()
{
   //do work on new thread
   //GetValueFromService(); <-- this is the function that returns an int from the web service, but it has to be called from another thread
}

How to call GetValueFromService() so that the step5() function returns the value calculated in the GetValueFromService() function?

kovacs lorand
  • 741
  • 7
  • 23
  • 4
    Why do you need to call async task many times? Just do all the 5 steps in one async task. If you need to split it to functions do it inside the asynctask that you are extending. And do you really need to return the value in int step5() or could you just set the value in onPostExcecute()? – wldchld Mar 10 '14 at 14:56
  • +1wldchld. Exactly what i was going to say – Kuffs Mar 10 '14 at 14:57
  • 1
    I can't do all 5 steps in one async task: the calling parameters of each step is calculated in the previous step. I need step 1 completed in order to call step 2. – kovacs lorand Mar 10 '14 at 15:04
  • You could try using listener mechanism. OnPostExecute call listener.thisJobIsDone(myParams); and whoever is owner, can call new asynctask. – Heisenberg May 21 '15 at 12:52

1 Answers1

0

Can you not do:

private class MyAsync extends AsyncTask<String, Integer, Long> {

    protected Long doInBackground(String... symbols) {
        step1();
        step2();
        step3();
        step4();
        step5();
    }

    private void step1(){}
    private void step2(){}
    private void step3(){}
    private void step4(){}
    private void step5(){}

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(Long result) {
    }
}
rvogel
  • 83
  • 1
  • 1
  • 9
  • Could you also add an explanation? – Robert May 21 '15 at 13:05
  • As nonspecific as the question is, I wouldn't know how to structure the steps. He claims to be nesting AsyncTasks, I am proposing creating methods for each step and calling them in order, in response to this comment: I can't do all 5 steps in one async task: the calling parameters of each step is calculated in the previous step. I need step 1 completed in order to call step 2. – rvogel May 21 '15 at 13:11