【问题标题】:Why Rxjava could cause memory leaking为什么 Rxjava 会导致内存泄漏
【发布时间】:2017-02-13 21:06:32
【问题描述】:

我正在使用 rxjava,发现如果在销毁活动之前未完成订阅,则存在内存泄漏的风险,因为“可观察对象保留对上下文的引用”。如果订阅未取消订阅 onDestroyed(来源: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 相关的内容。所以我能想到的只是因为在 subscribe 方法中定义了一个匿名 Action1 类,它持有对活动实例的引用。而 observable 又持有对动作的引用。我说的对吗?

谢谢

【问题讨论】:

标签: android memory-leaks rx-java


【解决方案1】:

.subscribe(new Action1&lt;Long&gt;() { }) 创建并存储 nested class,它作为任何非静态嵌套类都引用了包含类实例 - 在本例中为 Activity

要解决这个问题,你可以在Activity.onDestroySubscription.unsubscribemSubscription

【讨论】:

  • 确定mSubscription也无效。
猜你喜欢
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多