RxJava 三要素:
1.Observer: 观察者
2.Observable: 被观察者
3.subscribe: 订阅
目录
1. 需要在build.gradle 添加reactivex的依赖:
1. 需要在build.gradle 添加reactivex的依赖:
implementation 'io.reactivex.rxjava2:rxjava:2.1.4'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
2. 创建被观察者
var observable = Observable.create(object : ObservableOnSubscribe<Int> {
override fun subscribe(emitter: ObservableEmitter<Int>) {
Log.d(TAG, "Observable===== subscribe-currentThread name=${Thread.currentThread().name}")
emitter.onNext(1);
emitter.onNext(2);
emitter.onNext(3);
emitter.onComplete()
}
})
使用Observable.create() 创建, 并且实现接口ObservableOnSubscribe, 该接口实现的方法subscrible中有参数
ObservableEmitter, 使得可以向观察者发送数据
3.创建观察者
var observer = object : Observer<Int> {
override fun onComplete() {
Log.d(TAG, "Observer===== onComplete")
}
override fun onSubscribe(d: Disposable) {
Log.d(
TAG,
"Observer===== onSubscribe currentThread name=${Thread.currentThread().name}"
)
}
override fun onNext(t: Int) {
Log.d(TAG, "Observer===== onNext parm = $t")
}
override fun onError(e: Throwable) {
Log.d(TAG, "Observer===== onError")
}
}
Observer<Int> 泛型参数和被观察者中的 ObservableOnSubscribe<Int> 泛型参数一致
4.订阅
observable.subscribe(observer)
5.输出:
07-19 17:32:16.358 D 11692 11753 RxJavaTest: Observer===== onSubscribe currentThread name=Instr: androidx.test.runner.AndroidJUnitRunner
07-19 17:32:16.358 D 11692 11753 RxJavaTest: Observable===== subscribe-currentThread name=Instr: androidx.test.runner.AndroidJUnitRunner
07-19 17:32:16.358 D 11692 11753 RxJavaTest: Observer===== onNext parm = 1
07-19 17:32:16.358 D 11692 11753 RxJavaTest: Observer===== onNext parm = 2
07-19 17:32:16.358 D 11692 11753 RxJavaTest: Observer===== onNext parm = 3
07-19 17:32:16.359 D 11692 11753 RxJavaTest: Observer===== onComplete
附大牛参考网站