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

时间:2016-04-28 12:57:34

标签: android android-activity activity-lifecycle dagger-2

我看到如果在Activity中实例化Dagger 2 Component,那么它后来会在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这是非常有说服力的:"我不认为&#34} #39;必要但它定义的范围非常明确"。

1 个答案:

答案 0 :(得分:3)

  

如果我没有删除该实例[...]会怎样?

没什么。在调用onDestroy之后,活动对象将在某个时刻被垃圾收集。如果重新创建活动,它将是一个新对象。您的匕首组件也将与您的活动一起进行垃圾收集。我通常不会null onDestroy null我的组件,因为我觉得没必要。

如果你保持对你的活动的静态引用或者有其他类型的内存和活动泄漏,这将不会成立。但是如果你有那些,那么如果你$scope.myDataSource你的组件,它就不会产生太大的影响。