简体   繁体   English

在异步任务或异步任务上执行多个任务,并从执行后返回数据

[英]Execute multiple tasks on async task or in async task, and return data from postexecute

I have an API that I use to retrieve daily schedules on the live cable-tv for various channels. 我有一个API ,可用来在直播有线电视上检索各种频道的每日时间表。 I have a scenario in which I need a guidance as to which approach should work here. 我有一种情况,在这种情况下,我需要有关哪种方法应该在这里工作的指导。

Lets say I need schedules for 10 different channels from the API. 可以说我需要API的10个不同频道的时间表。

  • Should I execute 10 different async tasks for the retrieval of the required data? 是否应该execute 10个不同的async tasks来检索所需的数据?

Problem: How would I collect the data in an arraylist and return it once all execution is completed? 问题:如何将数据收集到arraylist并在完成所有执行后将其返回? How will I access the arraylist in my main function once onpostexecute returns the result? onpostexecute返回结果后,如何在主函数中访问arraylist?

  • Or I should just provide the list of channels to my single async task and make it build a single output of arraylist for my main function invoking it? 或者我应该只提供单个async task的通道列表,并使其为我的主函数调用构建单个arraylist输出?

Problem: Since I will be accessing a webservice for this purpose, will it make it run slow as compared to my 1st approach? 问题:由于我将为此目的访问webservice服务,与我的第一种方法相比,它会使它运行慢吗? Second problem with this approach is the same as I am having with my 1st one, I need to know when and how to get the complete resultset once the execution of the task is completed? 这种方法的第二个问题与我的第一个问题相同,我需要知道一旦完成任务执行,何时以及如何获得完整的resultset

Here is some code to explain the problem: 这是一些代码来说明问题:

//going with the first approach
//invoking my asynctask from an activity or another class

//I need a global arraylist which I can use after postexecute returns its result
ArrayList<String> channels = channelManager.getAllChannelsByRegion("xyz");
        final ArrayList<ChannelSchedule> schedules = new ArrayList<ChannelSchedule>();
        final ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
        for (int i = 0; i < channels.size(); ++i){
            AsyncInvokeURLTask task = null;
            try {
                task = new AsyncInvokeURLTask(
                    channels.get(i), context, new AsyncInvokeURLTask.OnPostExecuteListener() {
                        @Override
                        public void onPostExecute(String result) {
                            // TODO Auto-generated method stub                                                          
                            try {
//Need to add results to arraylist here...But cannot know when it ends completely
                                ChannelSchedule schedule = mapper.readValue(result, ChannelSchedule.class);
                                Log.v("channel name", schedule.getChannelName());
                                Log.v("channel date", schedule.getDate());
                                Log.v("channel thumb", schedule.getListOfShows().get(0).getShowThumb());
                                Log.v("channel time", schedule.getListOfShows().get(0).getShowTime());
                            } catch (JsonParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (JsonMappingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    });
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            task.execute();
        }

Please let me know if something is not clear or missing. 如果有不清楚或遗漏的地方,请告诉我。

Launching 10 AsyncTask is perfectly fine. 启动10 AsyncTask非常好。

You can keep a count of the number of pending requests. 您可以保留待处理请求的数量。 As OnPostExecute is run on the UI thread there are no risks of race condition. 由于OnPostExecute在UI线程上运行,因此没有竞争条件的风险。

private int numberOfPendingRequests;

public void MyFunc() {
  ArrayList<String> channels = channelManager.getAllChannelsByRegion("xyz");
  final ArrayList<ChannelSchedule> schedules = new ArrayList<ChannelSchedule>();
  final ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
  numberOfPendingRequests = channels.size();
  for (int i = 0; i < channels.size(); ++i) {
    schedules.add(null);
  }
  for (int i = 0; i < channels.size(); ++i) {
    AsyncInvokeURLTask task = null;
    final int index = i;  // final so it can be used in the onPostExecute.
    try {
      task = new AsyncInvokeURLTask(
        channels.get(i), context, new AsyncInvokeURLTask.OnPostExecuteListener() { 
          @Override public void onPostExecute(String result) {
            try {
              ChannelSchedule schedule = mapper.readValue(result, ChannelSchedule.class);
              Log.v("channel name", schedule.getChannelName());
              Log.v("channel date", schedule.getDate());
              Log.v("channel thumb", schedule.getListOfShows().get(0).getShowThumb());
              Log.v("channel time", schedule.getListOfShows().get(0).getShowTime());
              schedules.set(index, schedule);
              numberOfPendingRequests--;
              if (numberOfPendingRequests == 0) {
                // Everything is received, do stuff here.
              }
            } catch (JsonParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JsonMappingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          }
       });
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    task.execute();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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