RxLifecycle 笔

2017-01-05  本文已影响0人  Demon鑫

管理RxJava订阅后内存泄漏(内存管理)

0.添加依赖
compile 'com.trello:rxlifecycle:1.0'
compile 'com.trello:rxlifecycle-components:1.0'
1.使用
2.bindToLifecycle():[Activity/Fragment 使用方法相同]

使用compose() 完成Observable发布的事件和当前的组件绑定,实现生命周期同步。
从而实现当前组件生命周期结束时,自动取消对Observable订阅。

// 循环发送数字
Observable.interval(1, TimeUnit.SECONDS)
        .observeOn(AndroidSchedulers.mainThread())
        // 当Activity结束掉以后,Observable停止发送数据,订阅关系解除。
        .compose(this.<Long>bindToLifecycle())
        .subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                tvResult.setText("时间计数: " + aLong);
                Log.d(TAG, "时间计数器: " + aLong);
            }
        });
3.bindUntilEvent():[Activity/Fragment 使用方法相同]

指定在Activity其他的生命状态和订阅关系保持同步。

// 循环发送数字
Observable.interval(1, TimeUnit.SECONDS)
        .observeOn(AndroidSchedulers.mainThread())
        // 当Activity 执行 onDestroy() 方法时解除订阅关系
        .compose(this.<Long>bindUntilEvent(ActivityEvent.DESTROY))
        .subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
                tvResult.setText("时间计数: " + aLong);
                Log.d(TAG, "时间计数器: " + aLong);
            }
        });

2017-1-5 15:39:00

上一篇 下一篇

猜你喜欢

热点阅读