How to implement Dagger for worker classes in Dagger 2.16 ?(‘android.arch.work:work-runtime’)

How to implement Dagger for worker classes in Dagger 2.16?

public class SyncWorker extends  Worker {

    @Inject
    ISettingRepository settingRepository;

    @NonNull
    @Override
    public Result doWork() {

        sync();
        return Result.SUCCESS;
    }

    private void sync() {

    }
}

my AppComponent

@Singleton
@Component(modules = {
        AndroidSupportInjectionModule.class,
        BaseModule.class,
        ApiModule.class,
        UserDatabaseModule.class,
        SaleDatabaseModule.class,
        AppModule.class,
        ActivityBuilderModule.class
})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
    void inject(BaseApp app);

    @Override
    void inject(DaggerApplication application);

    @Component.Builder
    interface Builder {
        @BindsInstance

        Builder getApp(Application application);

        AppComponent build();
    }

}

How can I inject the settingRepository?

Answer

I was able to inject a worker with this approach.

  1. First, create a new method inside your app component that will inject your worker class.

    @Singleton
    public interface AppComponent extends AndroidInjector<YourApplicationClass> {
    
        @Component.Builder
        interface Builder {
    
            @BindsInstance
            AppComponent.Builder application(Application application);
    
            AppComponent build();
        }
    
        void inject(NotifWorker worker);
    }      
    
  2. Inside your application, build your dagger component as usual but assign it to a variable and make it global.

    public class YourApplicationClass implements HasActivityInjector {
    
      private AppComponent appComponent;
      @Override
      public void onCreate() {
          super.onCreate();
    
          appComponent = DaggerAppComponent.builder()
                  .application(this)
                  .build();
    
          appComponent.inject(this);
      }
    
      public AppComponent getAppComponent() {
          return appComponent;
      }
    }
    
  3. Inside your worker class, do something like this.

    public class NotifWorker extends Worker {
    
      @Inject
      ToBeInjectedClass toBeInjectedClass;
    
      public NotifWorker() {
        YourApplicationClass
            .getInstance()
            .getAppComponent()
            .inject(this)
      }
    }
    

Leave a Reply

Your email address will not be published. Required fields are marked *