如果我不在 Activity onDestroy() 中将 Dagger 2 Component 设置为 null,会发生什么情况?

What happens if I don't set Dagger 2 Component to null in Activity onDestroy()?

我看到如果有人在 Activity 中实例化 Dagger 2 组件,那么它稍后会在 onDestroy() 方法中为空,如 .

public class MyActivity {
    private MyActivityComponent component;
    //...

    public void onCreate() {
        component = Dagger_MyActivityComponent.builder()
            .myApplicationComponent(App.getComponent())
            .build()
            .inject(this);

        //...
    }

    public void onDestroy() {
        component = null;
    }
}

如果我不null那个实例会发生什么,会发生什么?

旁注: 我发现了有用的提示,为什么有人会将其设置为 null,这非常有说服力:"I don't think it's necessary but it defines scope pretty clear".

What happens if I don't null that instance [...]?

什么都没有。onDestroy 被调用后,activity 对象将在某个时候被垃圾收集。如果 activity 被重新创建,它将是一个新对象。你的匕首组件也将与你的 activity 一起被垃圾收集。我通常不会 null 我的组件 onDestroy 因为我认为它没有必要。

如果您保留对 activity 的静态引用或有其他类型的内存和 activity 泄漏,这将不成立 。但是如果你有这些,那么如果你 null 你的组件也不会有太大的区别。