结合 RxJava 了解 Android 内存泄漏

Understanding Android Memory Leaks in combination with RxJava

我还是不明白内存泄漏是怎么出现的。

我知道如果被使用的东西(比如单例)持有对某物的引用,否则这个对象不能被垃圾回收并且可用内存减少。

但这发生在什么范围内?我使用 RxBinding 从点击事件中创建和观察。 范围是 here 并且它表示:

Warning: The created observable keeps a strong reference to {@code view}. Unsubscribe to free this reference.

为什么这是必要的? 当我在 onCreate 中将手动侦听器设置为匿名内部 class 时,它会引用 activity,对吗?但是为什么整个 activity-view-observable-subscription 不能再被垃圾回收了?

When I set a manual listener as an anonymous inner class in onCreate it has a reference to to the activity, right? But why can't the whole activity-view-observable-subscription be garbage collected any more?

在这个简单的例子中,它可以被垃圾收集,你不应该有泄漏。

Why is [unsubscription] necessary?

这可能不是绝对必要的,就像您在上面给出的示例中那样。正如文档所述,这只是一个您应该注意的警告。但是,这是一个很好的做法。

问题是您可能正在 Rx 链中执行其他任务,这些任务可能会导致与 RxBinding 调用结合的泄漏。例如:

RxViews.clicks(clickableView)
    .flatMap(view -> getDataFromApi()
    .subscribe(data -> onDataLoaded(data));

在这种情况下,当使用另一个 Observable 单击按钮时,我们从 API 获取数据。该 Observable 仍然具有对点击 Observable 的引用,因此在我们的 API 调用 returns(可能永远不会)之前,引用的 View 不能被垃圾回收。