How Do You Implement Daggerservice
I've looked at the basics as well as the class, but being new to dagger (or even dagger 2) I have no idea how I'm suppose to use this Here is the dagger intent service: https://goo
Solution 1:
This does not answer the DaggerIntentService
problem, on purpose. dagger.android
packages more or less do the same thing you can do manually by setting relevant component and module for the Intent service. So you might try following approach:
ServiceComponent
@Subcomponent(modules = ServiceModule.class)publicinterfaceServiceComponent{
@Subcomponent.Builder
publicinterfaceBuilder {
Builder withServiceModule(ServiceModule serviceModule);
ServiceComponent build();
}
voidinject(MyService myService);
}
ServiceModule
@ModulepublicclassServiceModule{
privateMyService myService;
publicServiceModule(MyService myService){
this.myService = myService;
}
@ProvidespublicMyServiceprovideServiceContext(){
return myService;
}
@ProvidespublicSomeRepositoryprovideSomeRepository(){
returnnewSomeRepository();
}
}
Having in mind that you have root dagger component, for example ApplicationComponent
which you instantiate in application onCreate()
method, you'll need an additional public method in your application class.
ApplicationComponent
@Component(modules = ApplicationModule.class)
publicinterfaceApplicationComponent{
ServiceComponent.Builder serviceBuilder();
}
ApplicationModule
@Module(subcomponents = ServiceComponent.class)publicclassApplicationModule{
publicApplicationModule(MyApplication myApplication){
this.myApplication = myApplication;
}
@Providespublic MyApplication providesMyApplication(){
return myApplication;
}
}
MyApplication
publicclassMyApplicationextendsApplication{
ApplicationComponent applicationComponent;
@OverridepublicvoidonCreate(){
super.onCreate();
applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(newApplicationModule(this))
.build();
}
publicServiceComponentgetServiceInjector(MyService myService){
return applicationComponent.serviceBuilder().withServiceModule(newServiceModule(myService)).build();
}
Finally, your MyService
:)
MyService
public class MyService extends IntentService{
@Inject MyApplication application;
@Inject SomeRepository someRepository;
public onCreate(){
((MyApplication)getApplicationContext()).getServiceInjector(this).inject();
}
public void onHandleIntent(Intent intent){
//todo extract your data here
}
It might look complicated at first, but if you have dagger structure setup already, then its just two to three additional classes.
Hope you find it helpful. Cheers.
Post a Comment for "How Do You Implement Daggerservice"