Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to work with AsyncTasks in Class

I'm building an app which communicates with an API. I put all the API communication code and data handling in one API class so that every time I want to use the API I have a central spot where all the logic lies.

The thing is that for HTTPRequests it is strongly recommended to use AsyncTasks. As shown in the examples you create an AsyncTask by deriving the whole class.

My class consists of functions which need to be async because of the HTTP calls. Other don't.

My question: Do I just derive my whole API class from AsyncTask or shall I divide my API class even more in a normal and an async part?

like image 752
Ron Avatar asked Jan 20 '26 20:01

Ron


1 Answers

Create an interface with 2 kind of methods, one that don't execute on other threads and other that do. Make async methods accept a callback object to be notified when they're done. Example:

public interface MyAPI {
 //--this method runs an AsyncTask and calls supplied Callback object's methods when done
 public void fetchRemoteData(String input, Callback c);

 //--this method just processes input string locally and returns it
 public String doStuff(String input);
}

public interface Callback{
  public void onDone(int doneWhatCode, String result);
}

Implementation:

public class MyWebAPI implements MyAPI{
  @Override
  public void fetchRemoteData(String input, final Callback c){
        AsyncTask<String,Void,String> task = new AsyncTask<String,Void,String>(){

            @Override
            protected String doInBackground(String... strings) {
                String i = strings[0];

                //---connect, fetch data ----
                String result = "result";

                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                c.onDone(1,s);
            }
        };

      task.execute("new Input url");
    }

  @Override
  public String doStuff(String input){
    return input.replace("i","o");
  }
}

Let your API be exposed by these interfaces. This way you can keep it all together and also keep actual implementation separated for future changes.

like image 181
S.D. Avatar answered Jan 22 '26 11:01

S.D.