day36 rx全家桶

简介

Rx(Reactive Extensions)是一个库,用来处理事件和异步任务,在很多语言上都有实现,RxJava是Rx在Java上的实现。简单来说,RxJava就是处理异步的一个库,最基本是基于观察者模式来实现的。通过Obserable和Observer的机制,实现所谓响应式的编程体验。

官网:https://github.com/ReactiveX/RxJava
https://github.com/ReactiveX/RxAndroid

基本使用:
Observable被观察者;Observer 观察者;
线程调度:
observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
操作符
在这里插入图片描述

依赖

//rxlifecycle依赖->管理生命周期
    implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.1.0'
    //rxpermission->6.0动态权限申请框架
    implementation 'com.tbruyelle.rxpermissions2:rxpermissions:+'
    //okhttp依赖
    api 'com.squareup.okhttp3:okhttp:3.11.0'
    //okhttp日志拦截器
    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网络请求框架
    api 'com.squareup.retrofit2:retrofit:2.4.0'
    //retrofit下gson插件->网络请求回数据自动使用gson解析
    api 'com.squareup.retrofit2:converter-gson:2.4.0'
    //retrofit下使用rxjava线程调度插件
    api 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

常用注解

项目Value
@POSTpost 请求
@GETget请求
@HEADhead请求
@HTTPhttp 请求 可以设置达到上面任意请求
@Url指定
@Pathurl 替换
@Query查询字符串
@QueryMap比较多的查询字符串集合
@Field表单参数
@FieldMap表单参数集合
@Headers为方法添加请求响应头
@Header为方法参数添加请求响应头
@Part与Multipart注解结合使用,适合文件上传
@PartMap默认接受的类型是Map<String,RequestBody>
@Body请求上传的对象,发送非表单数据,如 传递json格式数据
@FormUrlEncodedForm表单数据,每个键值对需要使用@Field注解
@Multipart发送multipart数据,需要配合使用@Part @PartMap
@Streaming响应用字节流的形式返回.多用于下载大文件

代码

rx全家桶二次封装

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/");//公共接口地址,必须以/结尾
        builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        builder.addConverterFactory(GsonConverterFactory.create());
        retrofit = builder.build();
    }
}

获得的数据实体类

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接口

public interface Api {

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

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

    //上传图片
    @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;
        }
    }

    //申请权限方法
    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, "申请:"+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, "请求成功    "+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, "请求成功    "+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() {

                    }
                });
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值