Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between retrofit synchronous and asynchronous request? which one is better and why?

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?

like image 264
Mohammad Elsayed Avatar asked Jan 08 '18 13:01

Mohammad Elsayed


2 Answers

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

like image 87
Mohammad Elsayed Avatar answered Sep 27 '22 15:09

Mohammad Elsayed


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.

like image 37
EpicPandaForce Avatar answered Sep 27 '22 16:09

EpicPandaForce