我正在尝试在Android上探索Retrofit + OkHttp.这是我在网上找到的一些代码:
RestAdapter restAdapter = new RestAdapter.Builder().setExecutors(executor, executor) .setClient(new OkClient(okHttpClient)) .setServer("blah").toString()) .build();
如果我不使用执行程序服务,我的代码是否会在主线程上运行?我应该在新线程中发出Web请求吗?
可以为同步或异步执行声明Retrofit方法.
具有返回类型的方法将同步执行.
@GET("/user/{id}/photo") Photo getUserPhoto(@Path("id") int id);
异步执行需要方法的最后一个参数为a Callback
.
@GET("/user/{id}/photo") void getUserPhoto(@Path("id") int id, Callback<Photo> cb);
在Android上,回调将在主线程上执行.对于桌面应用程序,回调将在执行HTTP请求的同一线程上发生.
Retrofit还集成了RxJava以支持返回类型为的方法 rx.Observable
@GET("/user/{id}/photo") Observable<Photo> getUserPhoto(@Path("id") int id);
可观察请求是异步订阅的,并在执行HTTP请求的同一线程上观察到.观察在不同的线程(例如Android的主线程)上调用observeOn(Scheduler)
返回的Observable
.
注意:RxJava集成是实验性的.
返回值的方法是同步的.
@GET("/user/{id}/asset") Asset getUserAsset(@Path("id") int id);
要做到这一点异步你只需要添加一个回调.
@GET("/user/{id}/asset") void getUserAsset(@Path("id") int id, Callback<Asset> cb);
希望这可以帮助.
问候!