定义
Rxjava基于事件流、实现异步操作。
使用
引入依赖
implementation "io.reactivex.rxjava3:rxjava:3.1.2"
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
方法一
创建被观察者Observable及其产生的事件
Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(1);
emitter.onNext(2);
emitter.onNext(3);
emitter.onComplete();
}
});
创建观察者并定义响应事件的行为
采用Observer接口实现
Observer<Integer> observer = new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.d("main", "开始采用subscribe连接");
}
@Override
public void onNext(@NonNull Integer integer) {
Log.d("main", "next" + integer);
}
@Override
public void onError(@NonNull Throwable e) {
Log.d("main", "对Error事件作出响应");
}
@Override
public void onComplete() {
Log.d("main", "onComplete");
}
};
将观察者与被观察者关联起来(Subscribe)
observable.subscribe(observer);
此后Observable会发送对应任务,observer会依据数据进行任务处理
方法二
基于事件流直接完成任务生产及处理操作
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(1);
emitter.onNext(2);
emitter.onNext(3);
emitter.onComplete();
}
}).subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.d("main", "开始采用subscribe连接");
}
@Override
public void onNext(@NonNull Integer integer) {
Log.d("main", "next" + integer);
}
@Override
public void onError(@NonNull Throwable e) {
Log.d("main", "对Error事件作出响应");
}
@Override
public void onComplete() {
Log.d("main", "onComplete");
}
});
断开连接操作
Observer<Integer> observer = new Observer<Integer>() {
Disposable disposable;
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.d("main", "开始采用subscribe连接");
disposable = d;
}
@Override
public void onNext(@NonNull Integer integer) {
Log.d("main", "next" + integer);
disposable.dispose();
}
@Override
public void onError(@NonNull Throwable e) {
Log.d("main", "对Error事件作出响应");
}
@Override
public void onComplete() {
Log.d("main", "onComplete");
}
};
通过onSubscribe传入的Disposable参数进行连接关闭的操作。