Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Retrofit make network calls on main thread?

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 ?

like image 776
dev Avatar asked Jan 08 '14 21:01

dev


People also ask

Does retrofit run on main thread?

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.

How does retrofit work?

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.

What is the purpose of a retrofit interface?

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.

Is retrofit asynchronous or synchronous?

Retrofit supports synchronous and asynchronous request execution.


1 Answers

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.

like image 194
Jake Wharton Avatar answered Sep 23 '22 03:09

Jake Wharton