What are some methods that allow you to use one AsyncTask for different requests?

If we consider that there is a need to call different functions from different classes in onPostExecute .

  • It is difficult to offer something without a context, AsyncTask itself is customizable enough to push different types in onPostExecute. For example, I would suggest looking at Retrofit, which can itself execute requests asynchronously and transfer data to the main stream. What do you use for requests? - Serge Markov
  • OkHttp3. You need to perform requests to the API from different parts of the code, using different types of connections (POST, GET). - Marionette

1 answer 1

OKHTP has its own request execution mechanism asynchronously, described here https://github.com/square/okhttp/wiki/Recipes#asynchronous-get In most cases when you make small requests, most likely this will be enough than wrapping AsyncTask. The same mechanism uses Retrofit for an asynchronous call.

  • In this case, as I understand it, the number of requests = the number of OkHttp constructs. And you want to have one class in which you need to transfer the method name (String), connection type (String), parameters (Map), and it will execute it, and then the function in the source class (the initiator of the request) will be called. - Marionette
  • In general, untyped queries are a bad practice, since when changing parameters or long-term support, this will lead to the fact that you will need to maintain a large number of "magic" constants. Just the Retrofit itself generates the entire boilerplate, so you can have just one point for defining the names of the parameters and the name of the calling method. - Serge Markov
  • That is, it is more correct for each API method to write its own request mechanism? - Marionette
  • Accepted practice: using Retrofit, we make a description of each method and the returned model, make a separate layer ViewModel or Presetner in which the logic that requests data and displays them, processes the reactions. Most likely there will be several mappers from the services model in the ViewModel and the ViewModel binding in the View. - Serge Markov
  • Thanks, I will try. - Marionette