添加依赖
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.google.code.gson:gson:2.6.2'
使用代码
public class RxJavaActivity extends BaseActivity {
private static final String BASE_URL = "http://www.tngou.net/tnfs/api/";
Subscription subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
RequestService service = retrofit.create(RequestService.class);
subscription = service.getSingleImage("171")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
Observer<SingleImageBean> observer = new Observer<SingleImageBean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(SingleImageBean imageBean) {
Log.v("-->", imageBean.toString());
}
};
}
public interface RequestService {
@GET("show")
Call<SingleImageBean> getImage(@Query("id") String id);
@GET("show")
Observable<SingleImageBean> getSingleImage(@Query("id") String id);
}
请求结果
![这里写图片描述](https://img-blog.csdn.net/20160523143015947)
精彩推荐:
RxJava 和 Retrofit 结合使用的几个最常见使用方式举例
RxJava 与 Retrofit 结合的最佳实践