As I understand it, when scoping components and modules, instances that are (@)provided will live as long as the components that expose them exist.
More concretely, in the case of an @User scoped component, we can drop the @provided objects (provided by the modules) that are populated with user specific data when a user logs out. When a new user logs in, we should create a new Dagger component, that in turns exposes objects that will be populated with that (newly logged in) user specific data. These objects will in turn be kept alive as long as the component is not destroyed on log out.
My question is simply, how do we destroy a (sub)component on log out?
Is it sufficient that we just set the component to null so that it can be garbage collected, and create a new component manually through the builder?
Scope refers to the lifetime of an object. Consider an example of a simple class. largeScope — Its scope is tied to the lifetime of the class. It can be accessed anywhere in the class.
Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.
Components are essentially the glue that holds everything together. They are a way of telling Dagger 2 what dependencies should be bundled together and made available to a given instance so they can be used. They provide a way for a class to request dependencies being injected through their @Inject annotation.
You have to clean up after yourself. Destroying the component does not destroy its scoped objects and if you keep a reference to a scoped object longer than the components lifecycle it is usually a good source for memory leaks.
Dagger will inject or construct your objects, but what you do with those objects is entirely up to you. If you were to save a User
object obtained from your UserComponent
in a static variable it would obviously still be available after the component was garbage collected.
To prevent issues like this it is a good idea to not make use of static variables and to watch out when you hand short-living objects to longer-living ones.
If you have some UserScoped object it is not a good idea to reference it in your Application
, unless you remove the reference along with your component when a user logs out. The easiest approach would be to receate every fragment, service, and activity that had access to the user scoped component, and clean up your Application / Singleton that held the component.
If you do not "leak" any shorter lived objects to longer lived ones the garbage collector will take care of the rest.
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