使用场景:
一:Retrofit连用
二:基于Rxpermissions 等类库使用,RxBinding RxBus
导入
compile ‘io.reactivex.rxjava2:rxjava:2.0.1’
compile ‘io.reactivex.rxjava2:rxandroid:2.0.1’
Rxjava观察者模式
Observable novel=Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
emitter.onNext("连载1");
emitter.onNext("连载2");
emitter.onNext("连载3");
emitter.onComplete();
}
});
Observable.creat()进行生成对象,里面放的参数是个泛型,重写subscribe方法,里面有个emitter发射器.
emitter.next 无限调用
Observer<String> reader=new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
mDisposable=d;
Log.e(TAG,"onSubscribe");
}
@Override
public void onNext(String value) {
if ("2".equals(value)){
mDisposable.dispose();
return;
}
Log.e(TAG,"onNext:"+value);
}
@Override
public void onError(Throwable e) {
Log.e(TAG,"onError="+e.getMessage());
}
@Override
public void onComplete() {
Log.e(TAG,"onComplete()");
}
};
Disposable 方法是接收器.当不接收时候,disosable.dispose()取消订阅
novel.subscribe(reader);//一行代码搞定 开始订阅
Rxjava2.0是异步链式编程
Scheduler 是调度器,线程管理,他遵循哪个线程产生就在哪个线程消费的原则.线程之间不会发生变化,始终在一个线程.
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
emitter.onNext("连载1");
emitter.onNext("连载2");
emitter.onNext("连载3");
emitter.onComplete();
}
})
.observeOn(AndroidSchedulers.mainThread())//回调在主线程
.subscribeOn(Schedulers.io())//执行在io线程
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
Log.e(TAG,"onSubscribe");
}
@Override
public void onNext(String value) {
Log.e(TAG,"onNext:"+value);
}
@Override
public void onError(Throwable e) {
Log.e(TAG,"onError="+e.getMessage());
}
@Override
public void onComplete() {
Log.e(TAG,"onComplete()");
}
});