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?
OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.
HTTP is a synchronous protocol: the client issues a request and waits for a response. If you are using non-blocking (aka async) IO, the current thread of the client does not really have to wait, but can do other things (see above).
In synchronous operations tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one. In asynchronous operations, on the other hand, you can move to another task before the previous one finishes.
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
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With