brief introduction

Rx(Reactive Extensions) is a library used to handle events and asynchronous tasks. It is implemented in many languages. RxJava is the implementation of Rx in Java. In short, RxJava is a library for handling asynchrony, which is basically based on the observer pattern. Through the mechanism of Obserable and Observer, the so-called responsive programming experience is realized.

Official website: https://github.com/ReactiveX/RxJava
https://github.com/ReactiveX/RxAndroid

Basic use:
Observable observer; Observer observer;
Thread scheduling:
observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
Operator

Jurisdiction

//rxlifecycle dependency - > management lifecycle
    implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.1.0'
    //Rxpermission - > 6.0 dynamic permission application framework
    implementation 'com.tbruyelle.rxpermissions2:rxpermissions:+'
    //okhttp dependence
    api 'com.squareup.okhttp3:okhttp:3.11.0'
    //okhttp log interceptor
    api 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    //gson
    api 'com.google.code.gson:gson:2.8.5'
    //rxjava
    api 'io.reactivex.rxjava2:rxjava:2.2.3'
    //rxandroid
    api 'io.reactivex.rxjava2:rxandroid:2.1.0'
    //retrofit Network Request Framework
    api 'com.squareup.retrofit2:retrofit:2.4.0'
    //Gson plug-in under retrofit - > network request back data automatically using gson parsing
    api 'com.squareup.retrofit2:converter-gson:2.4.0'
    //Using rxjava thread scheduling plug-in under retrofit
    api 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

Common annotations

project Value
@POST post request
@GET get request
@HEAD head request
@HTTP http requests can be set to reach any of the above requests
@Url Appoint
@Path url replacement
@Query Query string
@QueryMap More sets of query strings
@Field Form parameter
@FieldMap Form parameter set
@Headers Adding a request response header to a method
@Header Adding request response headers for method parameters
@Part Used in conjunction with Multipart annotations for file upload
@PartMap The default accepted type is Map < String, RequestBody >
@Body Object requesting upload, sending non-form data, such as data in json format
@FormUrlEncoded Form form data, with @Field annotation for each key-value pair
@Multipart To send multipart data, you need to use @ Part @PartMap together
@Streaming Responses are returned as byte streams. They are mostly used to download large files.

Code

rx family barrel secondary packaging

public class RetrofitManager {

    private RetrofitManager() {
    }
    private static RetrofitManager retrofitManager = null;

    public static RetrofitManager getInstance(){
        if (retrofitManager == null){
            retrofitManager = new RetrofitManager();
        }
        return retrofitManager;
    }

    private Retrofit retrofit = null;
    public Retrofit getRetrofit(){
        if (retrofit == null)
            buildRetrofit();
        return retrofit;
    }

    private void buildRetrofit(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
        okBuilder.addInterceptor(interceptor);
        okBuilder.connectTimeout(1, TimeUnit.MINUTES);
        okBuilder.readTimeout(1,TimeUnit.MINUTES);
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.client(okBuilder.build());
        builder.baseUrl("http://169.254.163.202/yoho/");//Public Interface Address, No Ending/Ending
        builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        builder.addConverterFactory(GsonConverterFactory.create());
        retrofit = builder.build();
    }
}

Obtained data entity class

public class UploadEntity {
    public String statues;
    public String msg;
}
public class RecommendEntity {
    public String statues;
    public String msg;
}
public class GetEntity {
    public String statues;
    public String msg;
}

api interface

public interface Api {

    //get request
    @GET("Home_banner.php")
    Observable<GetEntity> requestGet();

    //post request
    @FormUrlEncoded
    @POST("brand_goods.php")
    Observable<RecommendEntity> requestPost(@Field("request")String request);

    //Upload pictures
    @Multipart
    @POST("upload_head.php")
    Observable<UploadEntity> uploadImg(@Part List<MultipartBody.Part> list);

}

acyivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_permission,R.id.btn_download,R.id.btn_post,R.id.btn_get,R.id.btn_upload})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btn_permission:
                Toast.makeText(this, "permission", Toast.LENGTH_SHORT).show();
                RequestPermission();
                break;
            case R.id.btn_download:

                break;
            case R.id.btn_post:
                retrofitPost();
                break;
            case R.id.btn_get:
                retrofitGet();
                break;
            case R.id.btn_upload:
                uploadImg();
                break;
        }
    }

    //Method of applying for permission
    private void RequestPermission(){
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        Toast.makeText(MainActivity.this, "Apply:"+aBoolean, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void retrofitGet(){
        RetrofitManager.getInstance().getRetrofit().create(Api.class)
                .requestGet().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GetEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(GetEntity getEntity) {
                        Toast.makeText(MainActivity.this, "Request successful    "+getEntity.msg, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void retrofitPost(){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("brand","1");
            jsonObject.put("page","1");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RetrofitManager.getInstance().getRetrofit().create(Api.class)
                .requestPost(jsonObject.toString())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RecommendEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(RecommendEntity recommendEntity) {
                        Toast.makeText(MainActivity.this, "Request successful    "+recommendEntity.msg, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void uploadImg(){
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/DCIM/Camera/tou1.png");
        Log.i("yj",file.getAbsolutePath()+file.getName());
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
        builder.addFormDataPart("uploadedfile","yj.png",requestBody);
        builder.addFormDataPart("userid","1");
        RetrofitManager.getInstance().getRetrofit().create(Api.class).uploadImg(builder.build().parts())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UploadEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UploadEntity uploadEntity) {
                        Toast.makeText(MainActivity.this, uploadEntity.msg, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}