should you create new Async Tasks for every different call or use the same one

前端 未结 4 821
[愿得一人]
[愿得一人] 2020-12-18 12:44

So I have an app that will make multipe HTTP Post/Gets

E.G. Login, getThisData, getThatData, sendThis, sendThat

Is it better to have a seperate AsyncTask to

相关标签:
4条回答
  • 2020-12-18 13:11

    Short answer is yes you should create a new AsncTask for each call.

    And if you interested, the long answer is;

    According to the Android's Asynctask documentation,

    • The goal of the AsyncTask is to take care of thread management for you and you should not worry about the threading mechanisms.
    • The Android Platform handles the pool of threads to manage the asynchronous operations. AsyncTasks are like consumables. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

    Happy asynchronous coding! :-)

    0 讨论(0)
  • 2020-12-18 13:13

    It depends on whether the tasks are independent on each other or whether they are interrelated. If independent you can handle this through the same async. For ex if you need some data from your login response and pass that value to getthis task you better use separate async. Make login a separate async, getthis ,get lthat sendthis sendthat can be in one async.

    0 讨论(0)
  • 2020-12-18 13:18

    If you want to create one instance of AsyncTask, and execute() it several times, no:
    Execute AsyncTask several times

    If you are asking about designing: whether you should write one class to get different kind of data? It really depends on your circumstances:
    If these HTTP call supposed to be sequential, you can put them in one AsyncTask class.
    If they have lot in common, just point to different URIs, you can write a call(String uri) method, and invoke that method in your AsyncTask. This case, I think one AsyncTask is also enough.

    0 讨论(0)
  • 2020-12-18 13:21

    You'll probably want to separate them, especially if their functionality in the pre/post executes differs. Try to organize your code into logical blocks. For example, if you have an Async Task to Login, and an Async task to, for example, download lots of document data via JSON, they will want separate Async tasks.

    However, lets say you have two separate API calls that return similar or partially the same data - if one returned the details of a file (name, size) and the other returned the same data but was a revision of a file - you could switch these in the same ASYNC because the post execute is going to perform the same (or partially the same) code to extract data from the JSON.

    0 讨论(0)
提交回复
热议问题