OKHttp supports both synchronous and asynchronous api. If I want to issue an async request, I can:
What is the difference between these 2 options? And which one is better?
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:
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.Activity
can be tagged with the Activity
instance. Then in onPause
or onStop
you can cancel all requests tagged with the Activity
instance.Call
mechanism this is much more efficient than the blocking version.So if you can, use Call.enqueue
!