一、RxLifeCycle使用方式
1、步骤
1、添加依赖
implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.2.2'
2、Activity/Fragment需继承RxAppCompatActivity/RxFragment
两种方式绑定生命周期
①bindToLifecycle()
②bindUntilEvent(event)
public Flowable<Integer> getIntervalData() {
return Flowable.create(new FlowableOnSubscribe<Integer>() {
@Override
public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
for (int i = 1; ; i++) {
LogUtils.error(TAG, "getIntervalData--emitter--:" + Thread.currentThread().getName() + "--:" + i + "-----iscancelled:" + emitter.isCancelled());
LogUtils.error(TAG, "getIntervalData--emitter--:" + Thread.currentThread().getName() + "--:" + TimeUtils.getNowString() + "-----request:" + emitter.requested());
if (emitter.isCancelled()) {
break;
}else {
while (emitter.requested() == 0) {
}
}
emitter.onNext(i);
}
}
}, BackpressureStrategy.ERROR);
}
public void interval() {
Disposable disposable = model.getIntervalData()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(((RxLifeCycleActivity) view).<Integer>bindToLifecycle())
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer aLong) throws Exception {
LogUtils.error(TAG, "rxJavaConcatExample--Consumer--:" + Thread.currentThread().getName() + "--:" + aLong);
}
});
}
public void intervalRxLifeCycle(ActivityEvent event) {
Disposable disposable = model.getIntervalData()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(((RxLifeCycleActivity) view).<Integer>bindUntilEvent(event))
.subscribe(new Consumer<Integer>() {
@Override
public void accept(Integer aLong) throws Exception {
LogUtils.error(TAG, "rxJavaConcatExample--Consumer--:" + Thread.currentThread().getName() + "--:" + aLong);
}
});
}
总结
1、在onStart方法中绑定,在onStop方法被调用后就会解除绑定,以此类推。
2、如果在onPause/onStop方法中绑定,那么就会在它的下一个生命周期方法(onStop/onDestory)被调用后解除绑定
3、如果要控制在某个生命周期结束,就直接使用bindUntilEvent(event)