I have really searched for this every where, I can make both synchronous and asynchronous data requests, but I can't actually understand which is asynchronous with what? and what is sync with what?
问题:
回答1:
call.execute()
runs the request on the current thread.
call.enqueue(callback)
runs the request on a background thread, and runs the callback on the current thread.
You generally don't want to run call.execute()
on the main thread because it'll crash, but you also don't want to run call.enqueue()
on a background thread.
回答2:
when you asynchronous, it means not in the foreground(it does not block the users interface while it accomplishes the given task), on other hand synchronous means in the foreground while your application execute things in the same thread the UI consuming.
In your case(making REST requests via retrofit or any other REST api) you must not make that in that foreground and you have to make in a background thread.
In the case of retrofit you have the following methods to make the request:
call.execute() // works in the foreground.
call.enqueue() // works in the background.
So you have a choice of two: either you make the call.enqueue directly or you can user call.execute but wrapped with a service(I mean you have to handle the background work your self).
回答3:
Retrofit is a type-safe HTTP client for Android and Java. And I would highly recommend using this over any other library.
Do you understand what is sync and async call, or what is blocking and non-blocking call?
To answer your question, any api call you do or any heavy or time-consuming task you do on Android, it should be non-blocking (async) as it should not block the Main or UI thread in Android.
Please read this article for more understanding
https://developer.android.com/guide/components/processes-and-threads.html
回答4:
Synchronous requests are declared by defining a return type.Synchronous methods are executed on the main thread. That means the UI blocks during request execution and no interaction is possible for this period. Using the .execute() method on a call object will perform the synchronous request. The deserialized response body is available via the .body() method on the response object.
Asynchronous requests don’t have a return type. Instead, the defined method requires a typed callback as last method parameter.Using asynchronous requests forces you to implement a Callback with its two callback methods: success and failure. When calling the asynchronous getTasks() method from a service class, you have to implement a new Callback and define what should be done once the request finishes.