Since the Worker
class is created by the framework (WorkerManager
), how can we use @Inject fields into the Worker
?
Asked
Active
Viewed 2,673 times
19

TylerH
- 20,799
- 66
- 75
- 101

Mehdi Jahed Manesh
- 2,228
- 2
- 17
- 34
-
https://github.com/google/dagger/issues/1183 – Tuby Jul 11 '18 at 11:39
-
I`d checked this link before I submit this question . Its not obvious the real implementation . @Tuby – Mehdi Jahed Manesh Jul 11 '18 at 14:05
-
1Just once look my sample https://github.com/saveendhiman/ComplexRecycler – Saveen Jul 15 '18 at 14:42
1 Answers
3
I am using these series of post for implementing dagger in my app and ProfileManager
is the class I wnat to inject
in my Worker
class.
UploadWorker
public class UploadWorker extends Worker {
@Inject
ProfileManager profileManager;
@Inject
@SuppressWarnings("WeakerAccess")
public UploadWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
Provider.getAppComponent().inject(this);
}
@NonNull
@Override
public Result doWork() {
profileManager.someMethod();
}
}
In Application class I am setting Appcomponent
in my Provider
class
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
AppComponent appComponent = DaggerAppComponent.builder().application(this).build();
appComponent.inject(this);
Provider.setAppComponent(appComponent);
return appComponent;
}
Provider
public class Provider {
private static AppComponent appComponent;
public static AppComponent getAppComponent() {
return appComponent;
}
public static void setAppComponent(AppComponent component) {
appComponent = component;
}
}
Appcomponent
@Singleton
@Component(modules = {
AndroidSupportInjectionModule.class,
ActivityBuilderModule.class,
ApiModule.class,
AppModule.class,
ViewModelModule.class
})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
@Override
void inject(DaggerApplication instance);
void inject(MyApplication app);
void inject(UploadWorker uploadWorker);
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
AppComponent build();
}
}

Levon Petrosyan
- 8,815
- 8
- 54
- 65
-
While we start worker, it doesn't has constructor in it, how are you using this? – Usman Rana Oct 15 '18 at 14:01
-
-
I see it is overridden from parent. This solution works but have you seen the 'https://gist.github.com/ThePredators/1702e79c5d3860f415c542da446420eb' it has different approach and plenty of work but didn't work for me. Any cons of your solution related to memory? – Usman Rana Oct 15 '18 at 14:07
-
Sorry not familiar with this solution, I don't think there is any disadvantages with my solution. – Levon Petrosyan Oct 15 '18 at 14:19