Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long do objects created by Dagger 2 remain in Android / how does Dagger 2 play with the Android Activity lifecycle?

Let's say we have a @Singleton application module that creates and returns a Hashmap for storing configuration data. If the configuration data is modified in the hashmap and the android application goes into the background and let's say onPause() and onStop() are called.

  • Will the hashmap that was created by dagger be destroyed?
  • If the app comes back into the foreground will the existing configuration data that was added to the hashmap still exist?
like image 250
dazza5000 Avatar asked Apr 27 '16 22:04

dazza5000


1 Answers

How does Dagger 2 play with the Android Activity lifecycle?

It won't. But you can.

Dagger ceates nothing but Pojos. Pojos that know about dependencies and give them to you when you require them. Nothing less and nothing more.

How you use those objects (components) is entirely up to you.

As most examples show it, there is an AppComponent in general, kept in the Application, and some sort of ActivtiyComponent for each Activity.

The AppComponent is kept in the application, to share its lifecycle—if the application gets killed or recreated, so does the component, so do your objects.

The ActivityComponent is created and kept within the activtiy. Once again, if the activity gets recreated, so does the component. It is nothing but an object assigned to a field inside your activity.

So why is there a difference between the app and the activity component?

The application component will only reference the application context, and provide classes that can be provided without further information.

The activity component will also have information about the activity. It can access views, fragment handlers, and so on: Activity stuff! You create a new component for every activity because if you don't use dagger you'd also use the current activity and not reference (and leak!) the same one everywhere.

To answer your question

If it is not clear by now, if you create your HashMap within the AppComponent (and @Scope it!), it will be the same HashMap in your entire application, if you properly use your AppComponent. It will be destroyed once the app gets terminated along with your Application instance.

If you create it within your ActivityComponent it will have the same lifecycle as the activity object. You would possibly have to reinitialize things in onCreate if savedInstanceState contains your data.


All this said, don't use static variables. If you assign your components to static variables they will destroy the setup and lead to memory leaks.

If you create your component in onCreate you will be fine without any other setup. Just don't use a static variable to hold the component, but make sure it lies within your activity or application respectively.

like image 180
David Medenjak Avatar answered Sep 24 '22 17:09

David Medenjak