Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 625
NeoWang Avatar asked Dec 07 '14 08:12

NeoWang


People also ask

Is OkHttp asynchronous?

OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.

Is HTTP request synchronous or asynchronous?

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).

What is synchronous and asynchronous in Android?

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.


1 Answers

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!

like image 116
Jake Wharton Avatar answered Sep 22 '22 04:09

Jake Wharton