How to manage multiple Async Tasks efficiently in Android

后端 未结 4 460

I have scenario where I will have to make six http calls to my server to get the data for six different items. These server calls cant be combined and they are meant to be t

4条回答
  •  孤街浪徒
    2020-12-05 16:25

    You could make a AsyncTask pool object that allows you to spoof a 'batch' http call.

    1. create an Observable collection of AsyncTasks, i'll refer to this collection as your Pool
    2. your Activity creates the AsyncTasks (but not execute yet) and adds them to the Pool
    3. Activity registers itself as an observer of the Pool
    4. Activity tells Pool to execute, Pool in turn calls execute on each of its Tasks
    5. When tasks complete (for both success and fail), they store the response data in the Pool, and the Pool marks the Task as being 'complete'
    6. Once all Tasks are marked as complete, Pool notifies the listening Activity

    General idea is for the Pool to know how many Tasks and pending, and to store the aggregate data of completed calls. Once all are finished, notify the observing Activity and pass back all the data.

    You'll have to work out how the AsyncTasks tell the Pool that they are finished. Maybe simply have an implementation of AsyncTask that takes a Pool on its constructor so that the Tasks have a reference to the Pool.

提交回复
热议问题