依赖地址
//http日志拦截器
implementation 'com.squareup.okhttp3:logging-interceptor:4.2.2'
//retrofit核心库
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
//retrofit辅助,gson解析的库
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
// 必要依赖,和Rxjava结合必须用到
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.2'
//切换到主线程的依赖
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
ApiService的定义
public interface ApiService {
@GET("xxxx/xxxxx/xxxxx")
Observable<School> getSchoolInfo();
@GET("xxxx/xxxxx/xxxxx")
Observable<Student> getStudentInfo();
}
现在模拟场景,先调用getScholInfo()接口,获取结果后再调用getStudentInfo()接口
final ApiService apiService = retrofit.create(ApiService.class);
apiService.getSchoolInfo().flatMap(new Function<School, ObservableSource<Student>>() {
@Override
public ObservableSource<Student> apply(School school) throws Exception {
//这里可以处理返回的结果
return apiService.getStudentInfo();//调用第二个接口
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Student>() {
@Override
public void accept(Student student) throws Exception {
//这里可以处理第二个接口的返回结果
}
});
网友评论