Is it possible to scope this and provide a release method in the module or elsewhere to prevent memory leaks. Ex. I need to close a database connection in onDestroy()
but it would be nice if this could be handled by the module itself.
Consider the following example* code.
*Read the error prone code at your own risk
@dagger.Module
@lombok.NoArgsConstructor
public class PersistenceModule {
@Provides
@Singleton
DatabaseProvider providesDatabaseHelper(Context context) {
return new DatabaseProvider(context);
}
}
public class SomeActivity extends Activity{
@javax.inject.Inject DatabaseProvider provider;
//..onCreate omitted where injection happens.
@Override
protected void onDestroy() {
//Close database and cleanup.
provider.release();
provider = null;
super.onDestroy();
}
}
Your sample seems error-prone, as you are scoping your DatabaseProvider
with a @Singleton
scope, but use and clean it up in an activity.
A Module
just helps creating objects—especially if there is no injectable constructor or it needs further initialization—and is not aware of further lifecycle events. It supplies its objects to a Component
, which just holds and creates the object graph needed to inject your classes. In the end both are just plain old java objects and a scope on a component is nothing more than syntactic sugar helping with compile time validation.
In any case, you should handle your cleanup at the same scope that you provide your dependency. @Singleton
scope should therefore be cleaned up in the application object that is also holding the application component. If you clean up a singleton scoped object in an activity, the next activity accessing it would be accessing an object in a closed state.
If every activity should have its own accessor and clean it up after being used, then you should switch to some activity based scope. Additional scopes are just annotations that you can create yourself.
All this said, I would not include "clean up" logic in my modules, because most people would not expect to find it there.
@Module
Annotates a class that contributes to the object graph.
Dagger is a dependency injection framework that provides dependencies for easier usage of interfaces and looser coupling of your classes. It is to reduce boiler plate code of object creation and what you do with the actual objects once you have them should not belong to the same code base creating them.
While it would still be possible to keep references to you modules, or make them implement some interface (still pojos!) and call them to clean up themselves in onDestroy
it would probably lead to more confusion than just doing the cleanup where others would expect it.
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