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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With