Kotlin+Retrofit+Rxjava开发(未完待续)

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);
      }
  });

未完待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值