解决rxjava导致的内存泄漏

版权声明:本文为博主原创文章,未经博主允许不得转载。

1.使用取消订阅管理器:CompositeSubscription,让CompositeSubscription持有所有的请求。统一取消。

//这代码是mvp中使用的 
public class LoginPresenter implements BasePresenter{
    private UserLoginContract mView;//当前的页面
    private CompositeSubscription msubscription;//管理所有的订阅

    public LoginPresenter(UserLoginContract mView) {
        this.mView = mView;
        this.mView.setPresenter(this);
        this.msubscription = new CompositeSubscription();

    }


    /**
     * 获取class
     */
    public void getClassInfo() {
        HashMap<String, String> map = new HashMap<>();
        map.put("id", "3");
        Subscription i  = ApiManger.getIntance().api.getClass(map)
                .flatMap(new Func1<BaseBean<List<SchoolClass>>, Observable<List<SchoolClass>>>() {
                    @Override
                    public Observable<List<SchoolClass>> call(BaseBean<List<SchoolClass>> listBaseBean) {
                        return new ApiInterceptor().flatResult(listBaseBean);
                    }
                })
                .compose(RxSchedulers.<List<SchoolClass>>IO_Main())
                .subscribe(new Subscriber<List<SchoolClass>>() {
                    @Override
                    public void onCompleted() {
                        //获取数据完成
                        mView.loginSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                       ApiException apiException = (ApiException) e;
                        mView.showToast(apiException.getRespMSg());
                    }

                    @Override
                    public void onNext(List<SchoolClass> schoolClasses) {
                        //得到数据,在页面可以进行数据绑定操作
                    }
                });
        this.msubscription.add(i);//把订阅加入管理集合中
    }

    @Override
    public void onDestroy() {
        //在activity结束生命周期的时候取消订阅,解除对context的引用
        if(msubscription != null){
            this.msubscription.unsubscribe();
        }
    }
}


public class BaseActivity extends AppCompatActivity {
    public BasePresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }
}

2.使用Rxlifecycle第三方库,完成Observable发布的事件和当前的组件绑定,实现生命周期同步。组件生命周期结束时,自动取消对Observable订阅。

项目依赖:
//rxlifecycle 生命周期同步
    compile 'com.trello:rxlifecycle:0.6.1'
    compile 'com.trello:rxlifecycle-components:0.6.1'

Rxlifecycle 使用

Activity/Fragment需继承RxAppCompatActivity/RxFragment,目前支持的有RxAppCompatActivity、RxFragment、RxDialogFragment、RxFragmentActivity。

一、bindToLifecycle()方法

在子类使用Observable中的compose操作符,调用,完成Observable发布的事件和当前的组件绑定,实现生命周期同步。从而实现当前组件生命周期结束时,自动取消对Observable订阅。

   Observable.interval(1, TimeUnit.SECONDS)
        .compose(this.bindToLifecycle())
            .subscribe(new Action1<Long>() { 
                @Override
                public void call(Long num) {
                    Log.i(TAG, "  " +num);
                }
            });

二、bindUntilEvent() 方法

使用ActivityEvent类,其中的CREATE、START、 RESUME、PAUSE、STOP、 DESTROY分别对应生命周期内的方法。使用bindUntilEvent指定在哪个生命周期方法调用时取消订阅。

 Observable.interval(1, TimeUnit.SECONDS)
         .compose(this.bindUntilEvent(ActivityEvent.PAUSE))  
         .subscribe(mSub);

3.自己取消订阅:subscription.unsubscribe() ;

public abstract class BaseFragment extends Fragment {
    protected Subscription subscription;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unsubscribe();
    }

    protected void unsubscribe() {
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荣•厚德载物

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值