为什么Rxjava可能导致内存泄漏 [英] Why Rxjava could cause memory leaking

查看:645
本文介绍了为什么Rxjava可能导致内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与rxjava一起玩,发现如果在活动被销毁之前未完成订阅,则存在内存泄漏的风险,因为可观察对象保留了对上下文的引用".如果未取消订阅onDestroyed(来源:

I'm playing with rxjava and found there is a risk of memory leak if a subscription is not completed before an activity is destroyed because "observables retain a reference to the context". One of the demos for such case is given as below, if the subscription is not unsubscribed onDestroyed (source: https://github.com/dlew/android-subscription-leaks/blob/master/app/src/main/java/net/danlew/rxsubscriptions/LeakingActivity.java):

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

    setContentView(R.layout.activity_leaking);

    // This is a hot Observable that never ends;
    // thus LeakingActivity can never be reclaimed
    mSubscription = Observable.interval(1, TimeUnit.SECONDS)
        .subscribe(new Action1<Long>() {
            @Override public void call(Long aLong) {
                Timber.d("LeakingActivity received: " + aLong);
            }
        });
}

但是我不确定为什么会存在这样的泄漏.我检查了Observable类,没有发现与Context相关的任何内容.因此,我能想到的是,因为在subscription方法中定义了一个匿名Action1类,该类保存对活动实例的引用.可观察对象又持有对该动作的引用.我说的对吗?

However I'm not sure why such a leak exists. I've checked the Observable class and seen nothing relevant to Context. So all I can think of is because there is an anonymous Action1 class defined within the subscribe method which hold a reference to the activity instance. And the observable in turn holds a reference to the action. Am I right?

谢谢

推荐答案

.subscribe(new Action1<Long>() { })创建并存储嵌套类,它是任何非静态嵌套类都引用包含类实例的实例-在本例中为Activity.

The .subscribe(new Action1<Long>() { }) creates and stores nested class which as any non-static nested class has reference to containg class instance - in this case the Activity.

要解决此问题,您可以 Subscription.unsubscribe < Activity.onDestroy

To resolve that you can Subscription.unsubscribe the mSubscription in the Activity.onDestroy

这篇关于为什么Rxjava可能导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆