1. 程式人生 > >RxJava與Retrofit學習記錄(一)

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();
    }
程式碼點選開啟連結