RxLifeCycle基础

一、RxLifeCycle使用方式

1、步骤

1、添加依赖

 implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.2.2'

2、Activity/Fragment需继承RxAppCompatActivity/RxFragment

两种方式绑定生命周期
①bindToLifecycle()
②bindUntilEvent(event)

RxLifeCycle基础_第1张图片
1535698100(1).jpg

    public Flowable getIntervalData() {
        return Flowable.create(new FlowableOnSubscribe() {
            @Override
            public void subscribe(FlowableEmitter 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).bindToLifecycle())
                .subscribe(new Consumer() {
                    @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).bindUntilEvent(event))
                .subscribe(new Consumer() {
                    @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)


RxLifeCycle基础_第2张图片
河马过河微信公众号.jpg

你可能感兴趣的:(RxLifeCycle基础)