简体   繁体   中英

Type-safe alternative for execute parameters in AsyncTask

There are two ways to pass arguments to an AsyncTask

  1. Define the first generic parameter and use a list/array of this typed and pass it through execute()
  2. Pass all necessary arguments through the constructor, store them in a field and access them in execute

I find the first approach more readable, but sometimes it lacks flexibility in terms of type-safety, for instance if you want to pass a String, an Integer and a Boolean it seems unclear how to approach this.

public Result doInBackground(String... params) {
   String param1 = params[0];
   int param2 = Integer.valueOf(params[1]);
   boolean param3 = Boolean.valueOf(params[2]);
   // ...
}

String parsing, putting it in a Bundle , etc. There is always a solution, but I find this unpleasing from a semantic/method signature point of view. Any alternatives?

Why not create a Class Holder for Example

static Class Holder {
  int i;
  String s;
  boolean b;
}

public Result doInBackground(Holder... params) {
   Holder holder = params[0];
   String holder.s;
  // ...
 }

then send it to the doBackground() through the execute().. i did it a lot of times when i want to send to web

this is just an example of crouse. Hope it helps.

You could use Loaders instead.

It can be cumbersome to start with, but you won't have any type-safe issues then, because it works in a complete different manner.

The main power of loaders is that they work with a manager that is bound to the lifecycle of the Activity/Fragment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM