一.简介
RxJava是ReactiveX在JVM上的一个实现,ReactiveX使用Observable序列组合异步和基于事件的程序的库;是一个基于事件流、实现异步操作的库。RxJava在Java环境下使用,它通过Observable(可观测对象)和Subscriber(订阅者)来实现异步编程模型。Observable可以发射出一系列的数据流,而Subscriber则负责处理这些数据流。利用各种操作符,我们可以对数据流进行变换、过滤、合并等操作,从而完成复杂的异步任务。
rx == 反应式 reactivex == 响应式编程:根据上一层的响应影响下一层的变化
Observable被观察者理解为起点,Observer观察者理解为终点,通过Subscribe连接两者
二、简单使用
1.bulid.gradle
java
implementation 'io.reactivex.rxjava3:rxandroid:3.0.2'
// Because RxAndroid releases are few and far between, it is recommended you also
// explicitly depend on RxJava's latest version for bug fixes and new features.
// (see https://github.com/ReactiveX/RxJava/releases for latest 3.x.x version)
implementation 'io.reactivex.rxjava3:rxjava:3.1.5'
2.使用rxjava下载网络图片
java
// 网络图片的链接地址
private final static String PATH = "https://pixiv.re/103070121.jpg";
public void showImage() {
//第二步
//起点
Observable.just(PATH)
//第三步
//图片下载需求
.map(new Function<String, Bitmap>() {
@Override
public Bitmap apply(String path) throws Throwable {
try {
Thread.sleep(2000);
URL url = new URL(path);
//建立网络连接对象
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5000);
int response = httpURLConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
})
// 加水印
.map(new Function<Bitmap, Bitmap>() {
@Override
public Bitmap apply(Bitmap bitmap) throws Throwable {
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(10);
Bitmap syBitmap = drawTextToBitmap(bitmap,"pixiv",paint,50,10);
return syBitmap;
}
})
// 日志记录需求
.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())
.subscribe(
//终点
new Observer<Bitmap>() {
//第一步
//订阅成功
@Override
public void onSubscribe(@NonNull Disposable d) {
layout.setVisibility(View.VISIBLE);
}
//第四步 显示图片
@Override
public void onNext(@NonNull Bitmap bitmap) {
image.setImageBitmap(bitmap);
}
//异常
@Override
public void onError(@NonNull Throwable e) {
}
//第五步 结束
@Override
public void onComplete() {
if (progressDialog != null) {
layout.setVisibility(View.GONE);
}
}
});
}
个人理解太浅,详细使用请参考: