At a glance: steps to build Retrofit2+RxJava2+ButterKnife framework

Posted by mobilekid on Thu, 02 Apr 2020 16:10:36 +0200

Step introduction:

  1. Add dependencies for Retrofit2 and RxJava2 libraries:
  2. Create a class that accepts the data returned by the server (the class used to process the data)
  3. Create an interface to describe network requests and configure network request parameters
  4. Create Retrofit instance
  5. Create an interface instance for a network request
  6. Send network request (synchronous, asynchronous)
  7. Processing data returned by the server

Code resolution:

① Add network permission and dependency, add network request permission in manifest, and add the following dependency to buildgrade file under app

   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
//  ① RxJava1.0+Retrofit2 dependency
//    compile 'io.reactivex:rxjava:1.1.0'
//    compile 'io.reactivex:rxandroid:1.1.0'
    //  ① RxJava2.0+Retrofit2 dependency
    compile 'io.reactivex.rxjava2:rxjava:2.1.0'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.amitshekhar.android:rx2-android-networking:1.0.0'//Support parsing json into Java objects

    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
//    The above three version numbers should be consistent
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    implementation 'com.google.code.gson:gson:2.8.2'

② Entity class, the entity class used to receive data (omitted)
③ Create an interface to describe network requests and configure network request parameters
Only Retrofit2 does not use RxJava interface:

package com.ytf.ppg.rxjava1demo.retrofit2;

import com.ytf.ppg.rxjava1demo.bean.MovieEntity;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * Created by ppg on 2018/3/12.
 * ③Network request interface, configure network request parameters
 * The call method is called when the object owning the instance
 * @Query GET Method query parameter, reflected in the URL, equivalent to the URL? After the k-v key value pair, url = *****? start=start&count=count”
 */

public interface MoviesService {
    @GET("top250")
    Call<MovieEntity> getTopMovie(@Query("start") int start,@Query("count") int count);
}

Interface using RxJava:

package com.ytf.ppg.rxjava1demo.retrofit2;

import com.ytf.ppg.rxjava1demo.bean.MovieEntity;


import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * Created by ppg on 2018/3/12.
 * ③Network request interface, configure network request parameters
 * The call method is called when the object owning the instance
 * @Query GET Method query parameter, reflected in the URL, equivalent to the URL? After the k-v key value pair, url = *****? start=start&count=count”
 */

public interface MoviesServiceRxJava {

    @GET("top250")Observable<MovieEntity> getMovies(@Query("start") int start, @Query("count") int count);
}

④ Implementation in acvitity:

package com.ytf.ppg.rxjava1demo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ytf.ppg.rxjava1demo.bean.MovieEntity;
import com.ytf.ppg.rxjava1demo.retrofit2.MoviesService;
import com.ytf.ppg.rxjava1demo.retrofit2.MoviesServiceRxJava;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class MainActivity extends AppCompatActivity {

    @BindView(R.id.mBtn_click)
    Button mBtn_click;
    @BindView(R.id.tv_mTv_content)
    TextView tv_mTv_content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.mBtn_click)
    public void onClick(){
//        getMovies();
        getMoviewByRxJava();
    }

    /**
     * The method of network request only using Retrofit2
     * (Unsealed, original)
     */
    private void getMovies() {
        String baseUrl = "https://api.douban.com/v2/movie/";
//      ④ Create an instance of Retrofit2
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
//       ⑤ Create an instance of the network request interface MoviesService and configure the network request parameters in the interface
        MoviesService moviesService=retrofit.create(MoviesService.class);
//        ⑥ Send network request
        Call<MovieEntity> call=moviesService.getTopMovie(0,10);
        call.enqueue(new Callback<MovieEntity>() {
            @Override
            public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) {
                tv_mTv_content.setText(response.toString());
            }

            @Override
            public void onFailure(Call<MovieEntity> call, Throwable t) {
                tv_mTv_content.setText(t.getMessage());
            }
        });

    }

    /**
     * Network request with RxJava
     */
    private void getMoviewByRxJava() {
        String baseUrl = "https://api.douban.com/v2/movie/";
        //      ④ Create an instance of Retrofit2
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
//       ⑤ Create an instance of the network request interface MoviesService and configure the network request parameters in the interface
        MoviesServiceRxJava moviesServiceRxJava=retrofit.create(MoviesServiceRxJava.class);
        moviesServiceRxJava.getMovies(0,10)
                .subscribeOn(io.reactivex.schedulers.Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MovieEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                       Toast.makeText(getApplicationContext(),"Implemented onSubscribe()Method",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(MovieEntity movieEntity) {
                        tv_mTv_content.setText( movieEntity.toString());
                        Toast.makeText(getApplicationContext(),"Implemented onNext()Method",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        tv_mTv_content.setText(e.getMessage().toString());
                        Toast.makeText(getApplicationContext(),"Implemented onError()Method",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        tv_mTv_content.setText("Finish!");
                        Toast.makeText(getApplicationContext(),"Implemented onComplete()Method",Toast.LENGTH_SHORT).show();
                    }
                });



    }
}

GitHub address: https://github.com/yangtianfu2018/Retrofit2RxJava2ButterKnife

Topics: network Retrofit Android ButterKnife