1.RX思维
为什么要学习RxJava:
- 改变思维(响应式编程思维:reactivex),编程效率提升
响应式编程:https://wiki.jikexueyuan.com/project/android-weekly/issue-145/introduction-to-RP.html
学习经典框架:
Github:https://github.com/ReactiveX/RxJava
Author:JakeWharton 被誉为Android之神
Rx系列:
官网:http://reactivex.io/#
Rx思维图:
2.RxJava实现下载图片
RxJava操作符知识参考:链接
实现思路:
代码示例:
// TODO 第二步
// 起点
Observable.just(PATH)
// TODO 第三步
// 需求:001 图片下载需求 PATH ---》 Bitmap
.map(new Function<String, Bitmap>() {
@NonNull
@Override
public Bitmap apply(@NonNull String path) throws Exception {
try {
//Thread.sleep(2000); // 睡眠2秒钟
URL url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5000); // 设置请求连接时长 5秒
int responseCode = httpURLConnection.getResponseCode();
// 才开始 request 拿到服务器的响应 200成功 404有问题 ...
Log.d("MainActivity",String.valueOf(responseCode));
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
})
// 需求:002 加水印
.map(new Function<Bitmap, Bitmap>() {
@NonNull
@Override
public Bitmap apply(@NonNull Bitmap bitmap) throws Exception {
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(88);
Bitmap shuiyingBitmap = drawTextToBitmap(bitmap, "哈哈哈", paint, 88, 88);
return shuiyingBitmap;
}
})
// 需求:003 日志记录需求
.map(new Function<Bitmap, Bitmap>() {
@NonNull
@Override
public Bitmap apply(@NonNull Bitmap bitmap) throws Exception {
Log.e(TAG, "什么时候下载了图片 apply: " + System.currentTimeMillis() );
return bitmap;
}
})
// 给上面的分配异步线程(图片下载操作)
.subscribeOn(Schedulers.io())
// 终点分配 Android主线程
.observeOn(AndroidSchedulers.mainThread())
// TODO 导火索 点燃了 开始执行
// 关联:观察者设计模式 关联 起点 和 终点 == 订阅
.subscribe(
// 终点
new Observer<Bitmap>() {
// TODO 第一步
// 订阅成功
@Override
public void onSubscribe(Disposable d) {
// 显示加载框
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("RXJava Derry run 正在加载中..");
progressDialog.show();
}
// TODO 第四步 显示图片 水印的Bitmap
// 上一层给我的响应
@Override
public void onNext(Bitmap bitmap) {
image.setImageBitmap(bitmap); // 显示到控件上
}
// 链条思维发生了异常
@Override
public void one rror(Throwable e) {
}
// TODO 第五步 整个链条思维全部结束
// 整个链条全部结束
@Override
public void onComplete() {
// 隐藏加载框
if (progressDialog != null)
progressDialog.dismiss();
}
});
}
// 图片上绘制文字 加水印
private final Bitmap drawTextToBitmap(Bitmap bitmap, String text, Paint paint, int paddingLeft, int paddingTop) {
Bitmap.Config bitmapConfig = bitmap.getConfig();
paint.setDither(true); // 获取跟清晰的图像采样
paint.setFilterBitmap(true);// 过滤一些
if (bitmapConfig == null) {
bitmapConfig = Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
canvas.drawText(text, paddingLeft, paddingTop, paint);
return bitmap;
}
运行结果:
3.自定义Observer解决项目中服务器响应的问题
请求服务器的结果Bean:
public class ResponseResult {
// 登录成功
private SuccessBean data; // 成功Bean
private int code;
private String message;
public ResponseResult(SuccessBean data, int code, String message) {
this.data = data;
this.code = code;
this.message = message;
}
public ResponseResult() {
}
public SuccessBean getData() {
return data;
}
public void setData(SuccessBean data) {
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "ResponseResult{" +
"data=" + data +
", code=" + code +
", message='" + message + '\'' +
'}';
}
}
成功Bean:
// 登录 注册 成功的 Bean 信息
public class SuccessBean {
private int id;
private String name;
public SuccessBean() {
}
public SuccessBean(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "SuccessBean{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
登陆引擎代码(模拟):
public class LoginEngine {
// 返回 起点
public static Observable<ResponseResult> login(String name, String pwd) {
// 最终返回 总Bean
ResponseResult responseResult = new ResponseResult();
if ("Derry".equals(name) && "123456".equals(pwd)) { // 登录成功
// 创建 成功 Bean
SuccessBean successBean = new SuccessBean();
successBean.setId(45674565);
successBean.setName("Derry登录成功");
/**
* {
* data:{ xxxxxxx 登录成功的Bean xxxxxxx SuccesBean 成功Bean }
* code:200
* message:"登录成功"
* }
*/
responseResult.setData(successBean);
responseResult.setCode(200);
responseResult.setMessage("登录成功");
} else { // 登录失败
/**
* {
* data:null
* code:404
* message:"登录错误"
* }
*/
responseResult.setData(null);
responseResult.setCode(404);
responseResult.setMessage("登录错误");
}
// 起点
return Observable.just(responseResult);
}
}
自定义Observer:
public abstract class CustomObserver implements Observer<ResponseResult> {
public abstract void success(SuccessBean successBean);
public abstract void error(String message);
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseResult responseResult) {
if (responseResult.getData() == null) {
error(responseResult.getMessage() + "请求失败,请Derry老师检查日志..");
} else {
success(responseResult.getData());
}
}
@Override
public void one rror(Throwable e) {
error(e.getMessage() + "请Derry老师检查日志,错误详情");
}
@Override
public void onComplete() {
}
}
需求: 如果登录成功 我只想拿到 SuccessBean
如果登录失败 我只想拿到 message String类型
MainActivity代码:
LoginEngine.login("Derry", "123456")
// 起点<总Bean>
.subscribe(new CustomObserver() {
@Override
public void success(SuccessBean successBean) {
Log.d("Derry", "成功的Bean 详情 success: SuccessBean: " + successBean.toString());
}
@Override
public void error(String message) {
Log.d("Derry", "String类型 error: message:" + message);
}
});
本文demo:https://github.com/gujunhe/RxJavaStudy.git