MobileCushion
MobileCushion

Reputation: 7095

What are the advantages/disadvantages on passing arguments to the AsyncTask constructor?

I am using AsyncTask and wondering what are the implications of passing the arguments to the constructor instead of passing them directly on the execute() call to the doInBackground(...) method, for example:

Call:

new SomeTask(bitmap, integer, "somestring").execute();

Class:

public class SomeTask extends AsyncTask<Void, Void, String> {
private String string;
private Bitmap image;
private int integer;

public SomeTask (Bitmap bmp, int someint, String s){
    this.image = bmp;
    this.string = s;
    this.integer = someint;
}

protected String doInBackground(Void... params) {       
    // whatever
    return "string";
}

@Override
protected void onPostExecute(String result){
    // whatever
}

}

What are the advantages/disadvantages regarding design, elegance, reuse and performance?

Thank you.

Upvotes: 10

Views: 1980

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006799

What are the advantages/disadvantages regarding design, ellegance, reuse and performance??

Use parameters to execute() if you will have an arbitrary number of the same type (e.g., several URLs as Strings that you want the task to download).

Use constructor parameters if you will have several parameters of distinct types, so you can take advantage of Java's compile-time type safety.

If you will have just one object to pass in (or none), both approaches are pretty much equivalent.

Upvotes: 15

Related Questions