4

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".

Community
  • 1
  • 1
Marian Paździoch
  • 8,813
  • 10
  • 58
  • 103

1 Answers1

4

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.

David Medenjak
  • 33,993
  • 14
  • 106
  • 134
  • "This will although not hold true if you keep static references to your activity or have some other sort of memory and activity leaks." could you please elaborate on this a little bit? – Marian Paździoch May 10 '16 at 06:55
  • 1
    @MarianPaździoch what of this is exactly is not clear to you? If you were to leak your activity, you would also leak the component if you don't set it null. if you leak your component and reference your activity, this will also leak your activity, no matter if you set your componentn null. And if you keep static variables set to either this will just lead to their leaking. – David Medenjak May 10 '16 at 08:22