需要引入的依赖包括:
compile 'com.squareup.retrofit2:retrofit:2.0.0' compile 'com.squareup.retrofit2:converter-gson:2.0.0' compile 'com.squareup.okhttp3:okhttp:3.2.0' compile 'com.squareup.okio:okio:1.6.0' compile 'io.reactivex:rxandroid:1.1.0'
这里不要遗漏converter-gson,或者可以使用simplexml解析
retrofit2在创建adapter时如需返回Observable需要注册CallAdapterFactory,这里和retrofit有区别,返回Callback不需要注册。
Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build();
接口定义:
public interface ApiService { @GET("Android/{pageSize}/{pageCount}") Observable<Response> users(@Path("pageSize")int pageSize, @Path("pageCount") int pageCount); }
调用:
api = retrofit.create(ApiService.class); Observable.just(params) .flatMap(new Func1<Map<String, Integer>, Observable<Response>>() { @Override public Observable<Response> call(Map<String, Integer> stringObjectMap) { return api.users(stringObjectMap.get("pageSize"),stringObjectMap.get("pageCount")); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Response>() { @Override public void call(ReceiveData response) { usersInfoList = response.results; listAdapter.notifyDataSetChanged(); } });
和Retrofit2单独使用有一些区别
首先,同样写个interface,这里是GitHubService.java,我们这次要实现获取官方提供的测试接口的数据
1 public interface GitHubService { 2 @GET("repos/{owner}/{repo}/contributors") 3 Observable<List<Contributor>> getUserInfoByObservable(@Path("owner") String owner, @Path("repo") String repo); 4 }
注意,上边的区别,retrofit2单独使用的时候是Call<List<Contributor>>,而rx使用的是Observable,可观察者对象
再写一个获取数据的工具类ParseUtils.java
1 public class ParseUtils { 2 3 public static GitHubService gitHubService = new Retrofit.Builder().baseUrl("https://api.github.com/") 4 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) 5 .addConverterFactory(GsonConverterFactory.create()).build().create(GitHubService.class); 6 7 }
这里也有一些区别,retrofit2单独使用时不需要addCallAdapterFactory(RxJavaCallAdapterFactory.create()),这里使用rx,如果没有这句话,会报Unable to create call adapter for rx.Observable错误
接下来在activity中使用
1 ParseUtils.gitHubService.getUserInfoByObservable("square", "retrofit") 2 .subscribeOn(Schedulers.newThread()) 3 .observeOn(AndroidSchedulers.mainThread()) 4 .subscribe(new Action1<List<Contributor>>() { 5 @Override 6 public void call(List<Contributor> contributors) { 7 //do somthing 8 } 9 });