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

猜你喜欢

转载自blog.csdn.net/taa1007/article/details/78441378