如何为工人类实现 Dagger? [英] How to implement Dagger for worker classes?
本文介绍了如何为工人类实现 Dagger?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
既然Worker
类是由框架(WorkerManager
)创建的,我们如何在Worker中使用@Inject字段
?
Since the Worker
class is created by the framework (WorkerManager
), how can we use @Inject fields into the Worker
?
推荐答案
你必须在要注入的模块中使用@Provides
注解提供类.
You have to provide class using @Provides
annotation in the module to inject.
首先创建一个包含提供类的模块的组件.
First create a component containing a module which will provide the class.
@Component(modules = {Module.class})
public interface Component1{
void inject(SyncWorker syncWorker);
}
模块类
@Module
public class Module{
@Provides
public ISettingRepository getSettingRepo(){
return new ISettingRepository();
}
}
现在在您的代码中编写一个构造函数,用于将组件注入到您的工作类中.
Now write in your code, a constructor that is used to inject the component into your worker class.
public class SyncWorker extends Worker {
@Inject
ISettingRepository settingRepository;
public SyncWorker(){
DaggerComponent1.builder().build().inject();
}
@NonNull
@Override
public Result doWork() {
sync();
return Result.SUCCESS;
}
private void sync() {
}
}
这篇关于如何为工人类实现 Dagger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文