I am trying to explore Retrofit+OkHttp on Android. Here's some code I found online :
RestAdapter restAdapter = new RestAdapter.Builder().setExecutors(executor, executor) .setClient(new OkClient(okHttpClient)) .setServer("blah").toString()) .build();
If I don't use executor service, will my code be running on the main thread ? Should I make web requests in a new thread hence ?
In retrofit, synchronous methods are executed in the main thread. This means that the UI is blocked during the synchronous request execution and no user interaction is possible in this period.
Retrofit is used to perform the following tasks: It manages the process of receiving, sending, and creating HTTP requests and responses. It alternates IP addresses if there is a connection to a web service failure. It caches responses to avoid sending duplicate requests.
Retrofit is a REST Client for Java and Android allowing to retrieve and upload JSON (or other structured data) via a REST based You can configure which converters are used for the data serialization, example GSON for JSON.
Retrofit supports synchronous and asynchronous request execution.
Retrofit methods can be declared for either synchronous or asynchronous execution.
A method with a return type will be executed synchronously.
@GET("/user/{id}/photo") Photo getUserPhoto(@Path("id") int id);
Asynchronous execution requires the last parameter of the method be a Callback
.
@GET("/user/{id}/photo") void getUserPhoto(@Path("id") int id, Callback<Photo> cb);
On Android, callbacks will be executed on the main thread. For desktop applications callbacks will happen on the same thread that executed the HTTP request.
Retrofit also integrates RxJava to support methods with a return type of rx.Observable
@GET("/user/{id}/photo") Observable<Photo> getUserPhoto(@Path("id") int id);
Observable requests are subscribed asynchronously and observed on the same thread that executed the HTTP request. To observe on a different thread (e.g. Android's main thread) call observeOn(Scheduler)
on the returned Observable
.
Note: The RxJava integration is experimental.
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