Reputation: 798
Greeting all!
Please help me to figure out if the scenario, I need to cope with, which meets the Dagger concepts.
I have to inject a class into my Activity which needs this activity to be created. The only way comes to my mind is to add the activity to the Model and use it in the object Provides method. does it sound like a normal usage scenario.
@Module
public class SampleDiModule {
private Activity activity;
public SampleDiModule(Activity activity){
this.activity = activity;
}
@Provides
@ModuleScope
public InjectedObject provideInjectedObject(){
return new InjectedObject.createForAcivity(activity)
}
}
My intention to inject an activity presenter, the presenter depends on a object which could be created only by the object factory in the following way
public MyPresentor(InjectedObject object){
}
InjectedObject object = InjectedObjectFactory.forActivity(this)
Thanks
Upvotes: 0
Views: 394
Reputation: 658
Ok, there are multiple ways to achieve this.
Two of them are on top of my mind.
First, using Dagger scopes. You can create @Activity scope which will manage objects that have life bound to life of particular activities. When creating dagger module that is scoped to Activity, you can pass an activity reference as constructor parameter, and then use it. Something like this (in pseudocode):
class ActivityScopedModule {
ActivityScopedModule(Activity: activity) {
this.activity = activity;
}
CustomObject provideCustomObject() {
return new CustomObject(this.activity);
}
}
Important thing is that modules that are scoped to activity must be instantiated from Activity.onCreate()
Here you can find more about creating dagger scopes: http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/ Or in this three-part series: https://android.jlelse.eu/dagger-2-part-i-basic-principles-graph-dependencies-scopes-3dfd032ccd82
Another approach, the easier one, would be to, instead of using static InjectedObjectFactory.forActivity(this)
, to make it as non-static class InjectedObjectFactory
, make it's instance in dagger module as new InjectedObjectFactory()
and then from activity you call myInjectedObjectFactory.forActivity(this)
and pass it to presenter.
Upvotes: 1