I see that if one instantiates a Dagger 2 Component in an Activity, then it's later nulled in the onDestroy()
method like seen 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;
}
}
What happens if I don't null
that instance and what would happen?
Side note: in comments I've found useful hint why one would set it to null
which is pretty convincing: "I don't think it's necessary but it defines scope pretty clear".
What happens if I don't null that instance [...]?
Nothing. After onDestroy
gets called the activity object will be garbage collected at some point. If the activity gets recreated it will be a new object. Your dagger component will also be garbage collected then along with your activity. I usually don't null
my components in onDestroy
because I deem it unnecessary.
This will although not hold true if you keep static references to your activity or have some other sort of memory and activity leaks. But if you have those it will not make much of a difference either if you null
your component.