RxJava与Retrofit学习记录(一)

原文地址https://gank.io/post/56e80c2c677659311bed9841

项目结构

1、原生Retrofit请求

  /**
     * 原生Retrofit请求
     */
    private void todo1() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();


        MoveService moveService = retrofit.create(MoveService.class);
        Call<MovieEntity> call = moveService.getTopMovie(0, 10);

        call.enqueue(new Callback<MovieEntity>() {
            @Override
            public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) {
                tv.setText(response.body().getTitle());
            }

            @Override
            public void onFailure(Call<MovieEntity> call, Throwable t) {

            }
        });
//        call.cancel();
    }

2、retrofit+rxjava简单实现

    /**
     * retrofit+rxjava
     */
    private void todo2() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

        MoveService moveService = retrofit.create(MoveService.class);
        moveService.getTopMovie2(0, 10).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<MovieEntity>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(MovieEntity movieEntity) {
                tv2.setText(movieEntity.getTitle());
            }
        });
        //        subscriber.unsubscribe();
    }

3、在2的基础上简单封装

private void todo3(){
        Subscriber subscriber = new Subscriber<MovieEntity>() {
            @Override
            public void onCompleted() {
                Toast.makeText(MainActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(MovieEntity movieEntity) {
                tv3.setText(movieEntity.getTitle());
            }
        };
        HttpMethods.getInstance().getTopMovie(subscriber, 0, 10);

    }

    HttpMethods:

    //构造方法私有
    private HttpMethods() {
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        retrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Constants.BASE_URL)
                .build();

        movieService = retrofit.create(MoveService.class);
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final HttpMethods INSTANCE = new HttpMethods();
    }

    //获取单例
    public static HttpMethods getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 用于获取豆瓣电影Top250的数据
     *
     * @param subscriber 由调用者传过来的观察者对象
     * @param start      起始位置
     * @param count      获取长度
     */
    public void getTopMovie(Subscriber<MovieEntity> subscriber, int start, int count) {
        movieService.getTopMovie2(start, count)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

4、3的简单封装的基础上实现泛型对json最外层相同数据进行封装

 private void todo4(){
        Subscriber subscriber = new Subscriber<HttpResponse<List<SubjectsEntity>>>() {
            @Override
            public void onCompleted() {
                Toast.makeText(MainActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(HttpResponse<List<SubjectsEntity>> movieEntity) {
                tv4.setText(movieEntity.getTitle());
            }
        };
        HttpMethods.getInstance().getTopMovie3(subscriber, 0, 10);
    }
注意
List<SubjectsEntity>

5、对于返回的json产生的业务进行封装

private void todo5(){
        Subscriber subscriber = new Subscriber<List<SubjectsEntity>>() {
            @Override
            public void onCompleted() {
                Toast.makeText(MainActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(List<SubjectsEntity> movieEntity) {
                tv5.setText(movieEntity.get(0).getTitle());
            }
        };
        HttpMethods.getInstance().getTopMovie4(subscriber, 0, 10);
    }

6、接口请求时等待封装

private void todo6(){
        ProgressDialogHandler mHandler=new ProgressDialogHandler(this, true, new ProgressCancelListener() {
            @Override
            public void onCancelProgress() {
                System.out.println("cancle==========");
            }
        });
        ProgressSubscriber<List<SubjectsEntity>> subscriber=new ProgressSubscriber<List<SubjectsEntity>>(subscriberOnNextListener,this,mHandler);
        HttpMethods.getInstance().getTopMovie4(subscriber, 0, 10);

//        subscriber.onCancelProgress();
    }
代码点击打开链接
阅读更多
想对作者说点什么? 我来说一句

rxjava retrofit 框架

2018年01月05日 141KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭