Retrofit+RXJava的使用

首先我们在app的build.gradle中配置:

RXJava配置:

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.bwie.rxjava"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        //lambda表达式配置
        jackOptions {
            enabled true
        }
    }
    compileOptions{
        //设置java8
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'


API:

public class API {
    public static final String  path = "http://api.tianapi.com/";
}

APIService:

public interface ApiService {

    @GET("social/?key=71e58b5b2f930eaf1f937407acde08fe&num=20")
    Observable<Bean>  getpath();
}

MainActivity:

private void gethome() {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(API.path).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    ApiService apiService  = retrofit.create(ApiService.class);
    rx.Observable<Bean> getpath = apiService.getpath();
    getpath.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers
            .mainThread())
            .subscribe(new Observer<Bean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(Bean bean) {
            List<Bean.NewslistBean> list = bean.getNewslist();
            RecyclerAdapter ra = new RecyclerAdapter(MainActivity.this , list) ;
            recycler.setAdapter(ra);
            Log.d("MainActivity", "onNext: "+bean.getNewslist().get(0).getTitle());
            Toast.makeText(MainActivity.this , bean.getNewslist().get(0).getTitle() , Toast.LENGTH_SHORT).show();
        }
    });
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值