简介
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 |
---|---|
@POST | post 请求 |
@GET | get请求 |
@HEAD | head请求 |
@HTTP | http 请求 可以设置达到上面任意请求 |
@Url | 指定 |
@Path | url 替换 |
@Query | 查询字符串 |
@QueryMap | 比较多的查询字符串集合 |
@Field | 表单参数 |
@FieldMap | 表单参数集合 |
@Headers | 为方法添加请求响应头 |
@Header | 为方法参数添加请求响应头 |
@Part | 与Multipart注解结合使用,适合文件上传 |
@PartMap | 默认接受的类型是Map<String,RequestBody> |
@Body | 请求上传的对象,发送非表单数据,如 传递json格式数据 |
@FormUrlEncoded | Form表单数据,每个键值对需要使用@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() {
}
});
}
}