Question

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 ?

Was it helpful?

Solution

The method that return a value does it Synchronously.

@GET("/user/{id}/asset")
Asset getUserAsset(@Path("id") int id);

To do it Asynchronous all you need is to add a Callback.

@GET("/user/{id}/asset")
void getUserAsset(@Path("id") int id, Callback<Asset> cb);

Hope this Helps.

Regards!

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top