Android Retrofit 是否在主线程上进行网络调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21006807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Retrofit make network calls on main thread?
提问by Jaguar
I am trying to explore Retrofit+OkHttp on Android. Here's some code I found online :
我正在尝试在 Android 上探索 Retrofit+OkHttp。这是我在网上找到的一些代码:
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 ?
如果我不使用 executor 服务,我的代码会在主线程上运行吗?因此,我应该在新线程中发出 Web 请求吗?
采纳答案by Martin Cazares
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!
问候!
回答by Jake Wharton
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
.
异步执行要求方法的最后一个参数是 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.
在 Android 上,回调将在主线程上执行。对于桌面应用程序,回调将发生在执行 HTTP 请求的同一线程上。
Retrofit also integrates RxJava to support methods with a return type of rx.Observable
Retrofit 还集成了 RxJava 以支持返回类型为 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
.
可观察请求是异步订阅的,并在执行 HTTP 请求的同一线程上观察。要在不同的线程(例如 Android 的主线程)observeOn(Scheduler)
上观察返回的Observable
.
Note: The RxJava integration is experimental.
注意:RxJava 集成是实验性的。