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

NeoWang picture NeoWang · Dec 7, 2014 · Viewed 12.1k times · Source

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. Issue a OKhttp asynchronous api.

What is the difference between these 2 options? And which one is better?

Answer

Jake Wharton picture Jake Wharton · Dec 7, 2014

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!