1.项目框架导入:
kotlin:
需先安装kotlin插件。
//-----项目下build.gradle设置
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
//-----app的build.gradle设置
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
...
//kotlin导入
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "org.jetbrains.anko:anko-common:$anko_version"
retrofit:
//retrofit网络请求
compile 'com.squareup.retrofit2:retrofit:latest.release'
//添加gson解析
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
rxjava:
//rxjava框架导入
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'// 针对rxjava2.x(adapter-rxjava2的版本要 >= 2.2.0)
2.retrofit适配rxjava的使用:
Converter是对于Call中T的转换,而CallAdapter则可以对Call转换,这样的话Call中的Call也是可以被替换的,而返回值的类型就决定你后续的处理程序逻辑,同样Retrofit提供了多个CallAdapter,这里以RxJava的为例,用Observable代替Call
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:4567/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// 针对rxjava2.x
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
//接口设计:
public interface BlogService {
@POST("/blog")
Observable<Result<List<Blog>>> getBlogs();
}
//使用:
BlogService service = retrofit.create(BlogService.class);
service.getBlogs(1)
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<Result<List<Blog>>>() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.err.println("onError");
}
@Override
public void onNext(Result<List<Blog>> blogsResult) {
System.out.println(blogsResult);
}
});
未完待续