Using OKHttp, what is the difference between synchronous request in AsyncTask and OKhttp Asynchronous request?

前端 未结 2 703
花落未央
花落未央 2020-12-04 10:36

OKHttp supports both synchronous and asynchronous api. If I want to issue an async request, I can:

  1. Use a AsyncTask, and issue OKhttp synchronous api.
相关标签:
2条回答
  • 2020-12-04 10:49

    Quite a lot differs!

    Using AsyncTask for HTTP requests is pretty much one of the worst things you can do on Android. It's fraught with problems and gotchas that are best unconditionally avoided. For example, you cannot cancel a request during execution. The patterns of using AsyncTask also commonly leak a reference to an Activity, a cardinal sin of Android development.

    OkHttp's async is vastly superior for many reasons:

    • It supports native canceling. If a request is in-flight, the reference to the Callback is freed and will never be called. Additionally, if the request has not started yet it never will be executed. If you are using HTTP/2 or SPDY we can actually cancel mid-request saving bandwidth and power.
    • It supports tagging multiple requests and canceling them all with a single method call. This means every request you make in, say, an Activity can be tagged with the Activity instance. Then in onPause or onStop you can cancel all requests tagged with the Activity instance.
    • If you are using HTTP/2 or SPDY requests and responses are multiplexed over a single connection to the remote server and by using the asynchronous Call mechanism this is much more efficient than the blocking version.

    So if you can, use Call.enqueue!

    0 讨论(0)
  • 2020-12-04 10:57

    Nothing much. OKHttp async is OKHttp API driven. So as long as you bundle the jars together for all platforms you should be good. AsyncTask is Android way of doing things.

    However since Honeycomb Async task runs the tasks sequentially and not in parallel. This means that though the execute method of AsyncTask spans a new thread which runs your job away from the UI thread but all the tasks sent to one AsyncTask run in the same spanned thread.

    So for 3 tasks submitted u don't get 3 threads they all run sequentially on a single spanned thread. With OKHttp you can achieve true parallelism using callbacks and async GET and POST.

    Though you can do true parallelism in AsyncTask methods as well (check the overloaded execute methods in AsyncTask) but default Android behavior is not to do so.

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