我看到如果有人在 Activity 中实例化 Dagger 2 组件,那么它稍后会在 onDestroy()
方法中为空,如 here 所示.
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
那个实例会发生什么,会发生什么?
旁注:in comments我发现了有用的提示,为什么有人会将其设置为 null
,这非常有说服力:“我认为这不是必需的,但它定义的范围非常清楚”。
最佳答案
What happens if I don't null that instance [...]?
Nothing. onDestroy
被调用后, Activity 对象将在某个时候被垃圾回收。如果 Activity 被重新创建,它将是一个新对象。你的 Dagger 组件也将随你的 Activity 一起被垃圾收集。我通常不会在 onDestroy
中null
我的组件,因为我认为它没有必要。
如果您保持对您的 Activity 的静态引用或有其他类型的内存和 Activity 泄漏,这虽然不成立。但是,如果您拥有这些,那么即使您null
您的组件也不会有太大的不同。
关于android - 如果我不在 Activity onDestroy() 中将 Dagger 2 Component 设置为 null 会怎样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36915413/