RxJava RxAndroid Retrofit实践结合

1.RxJava与Retrofit结合

1 build.gradle文件中添加如下内容

compile 'com.android.support:appcompat-v7:23.4.0'
compile 'io.reactivex:rxjava:1.0.10'
compile 'io.reactivex:rxandroid:1.2.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.google.code.gson:gson:2.6.2'
2 单纯使用Retrofit
2.1. 首先我们要创建一个接口取名为MovieService,代码如下:
public interface MovieService {

    //GET
    @GET("top250")             //"top250"  接口名
    Call<MovieInfo> getMovieInfoByGET(@Query("start") int start,@Query("count") int count );    //括号里面是参数名称

    //POST
    @FormUrlEncoded
    @POST("top250")
    Call<MovieInfo> getMovieInfoByPOST(@Query("start") int start,@Query("count") int count );

}

2.2 Activity中实现

 String url = "https://api.douban.com/v2/movie/";  //接口地址
//1.创建Retrofit对象
 Retrofit retrofit = new Retrofit.Builder()
         .baseUrl(url+"/")
         .addConverterFactory(GsonConverterFactory.create())
         .build();

 //2.创建服务对象
 //3 .创建访问API的请求
 MovieService service = retrofit.create(MovieService.class);
 Call<MovieInfo> call = service.getMovieInfoByGET(0,1);

 //4.异步调用
 call.enqueue(new Callback<MovieInfo>() {
     @Override
     public void onResponse(Call<MovieInfo> call, Response<MovieInfo> response) {

         if(response!=null && response.body()!=null && response.body().subjects!=null){
             for (MovieInfo.CastsBean castsBean : response.body().subjects.get(0).casts) {
                 Log.e("onResponse===",castsBean.toString());
             }
         }

     }

     @Override
     public void onFailure(Call<MovieInfo> call, Throwable t) {
         Log.e("onFailure===",t.toString());
     }
 });
3 Retrofit结合RxJava

添加Retrofit对Rxjava的支持需要在Gradle文件中添加
compile ‘com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4’

3.1 重新定义MovieService, 返回一个Observable对象

    //GET
    @GET("top250")             //"top250"  接口名
    Observable<MovieInfo> getMovieInfoByGET2(@Query("start") int start, @Query("count") int count );    //括号里面是参数名称

    //POST
    @FormUrlEncoded
    @POST("top250")
    Observable<MovieInfo> getMovieInfoByPOST2(@Query("start") int start,@Query("count") int count );

3.2 Activity中实现

String url = "https://api.douban.com/v2/movie/";  //接口地址
        //1.创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url+"/")
                .addConverterFactory(GsonConverterFactory.create())         //添加GSON支持
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())  //添加Rxjava支持
                .build();

        //2.创建服务对象
        //3 .创建访问API的请求
        MovieService service = retrofit.create(MovieService.class);
        Observable<MovieInfo> observable = service.getMovieInfoByGET2(0,1);

        //4.异步调用
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MovieInfo>() {
                    @Override
                    public void onCompleted() {
                        Log.e("onCompleted","解析完成");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("onError",e.toString());
                    }

                    @Override
                    public void onNext(MovieInfo movieInfo) {

                        if(movieInfo!=null && movieInfo.subjects!=null && movieInfo.subjects.size()>0){

                            for (MovieInfo.CastsBean info: movieInfo.subjects.get(0).casts) {

                                Log.e("onNext",info.toString());
                            }
                        }
                    }
        });
4封装

4.1 //网络请求帮助类

public class HttpHelper {

    private Retrofit retrofit;
    private final MovieService movieService;

    private HttpHelper(String url){

        Retrofit retrofit = createRetrofit(url);
        movieService = retrofit.create(MovieService.class); //2. 创建MovieService对象
    }

    private  static HttpHelper helper;

    //1.对象单例
    public static HttpHelper getHelper(String url){
       if(helper==null){
           synchronized (HttpHelper.class){
               if(helper==null){
                   helper = new HttpHelper(url);
               }
           }
       }
        return helper;
    }


    //2.创建retrofit对象
    private Retrofit createRetrofit(String url){

        retrofit = new Retrofit.Builder()
                .baseUrl(url +"/")
                .client(new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build())  //设置超时时间为10秒钟
                .addConverterFactory(GsonConverterFactory.create())   //添加GSON支持
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())  //添加RxJava支持
                .build();
        return retrofit;
    }

    //3 获取电影信息
    public void getMoveInfo(Subscriber<MovieInfo> subscriber,int start, int count){

        Observable<MovieInfo> observable = movieService.getMovieInfoByGET2(0, 1);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

    }

}

4.2 Activity中实现

subscriber = new Subscriber<MovieInfo>() {
            @Override
            public void onCompleted() {
                Log.e("onCompleted","解析完成");
            }

            @Override
            public void onError(Throwable e) {

                Log.e("onError",e.toString());
            }

            @Override
            public void onNext(MovieInfo info) {

                if(info!=null && info.subjects!=null && info.subjects.size()>0){

                    for (MovieInfo.CastsBean castsBean: info.subjects.get(0).casts) {

                        Log.e("onNext",castsBean.toString());
                    }
                }
            }
        };
        HttpHelper.getHelper(url).getMoveInfo(subscriber,0,1);

代码下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值