Retrofit 结合RxJava 使用
GRADLE
compile 'com.squareup.retrofit2:retrofit:2.1.0'
//支持rxjava
compile 'io.reactivex:rxjava:1.1.6'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
//支持gson解析
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
//支持日志输出
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
最基本的例子
定义接口
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
结合RxJava实现接口
//日志输出,可以不用
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//需要添加这一句支持RxJava
.client(httpClient);
.build();
GitHubService service = retrofit.create(GitHubService.class);
结合RxJava调用接口
service.subscribeOn(Schedulers.newThread())//请求在新的线程中执行
//每次observeOn设置线程只表示在下次设置observeOn之前的回调运行的线程,像这样一次有可能可以添加很多回调,可以设置多个observeOn
.observeOn(Schedulers.io()) //请求完成后在io线程中执行,即紧接着的回调在io线程操作,如果里面不是io操作,可以变为其他线程
//这个看需要,不一定有,这个的意思是服务端返回结果解析成ResInfo后传给Subscriber之前的操作
.doOnNext(new Action1<ResInfo>() {
@Override
public void call(ResInfo resInfo) {
//操作
}
})
.observeOn(AndroidSchedulers.mainThread())//最后在主线程中执行
//最后的结果传送给Subscriber
.subscribe(new Subscriber<UserInfo>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
//请求失败
}
@Override
public void onNext(UserInfo userInfo) {
//请求成功,获得最后的结果
}
});
解释1 接口定义
可以设置path从参数传入,还可以设置query参数从参数传入
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user, @Query("id") String id);
@GET("users/repos")
Call<List<Repo>> listRepos(@Query("id") String id);
@GET("users/list?sort=desc")
Call<List<Repo>> listRepos(@Query("id") String id);
//允许Map形式的参数
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
同理还可以是POST
@FormUrlEncoded
@POST("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user, @Field("id") String id);
解释2 Scheduler线程
-
Schedulers.computation():用于计算型工作例如事件循环和回调处理,不要在I/O中使用这个函数(应该使用Schedulers.io()函数);
-
Schedulers.from(executor):使用指定的Executor作为Scheduler;
-
Schedulers.immediate():在当前线程中立即开始执行任务;
-
Schedulers.io():用于I/O密集型工作例如阻塞I/O的异步操作,这个调度器由一个会随需增长的线程池支持;对于一般的计算工作,使用Schedulers.computation();
-
Schedulers.newThread():为每个工作单元创建一个新的线程;
-
Schedulers.test():用于测试目的,支持单元测试的高级事件;
-
Schedulers.trampoline():在当前线程中的工作放入队列中排队,并依次操作。
-
AndroidSchedulers.mainThread(): UI线程
混淆配置
-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions

浙公网安备 33010602011771号