Hello, I am writing an android application in which I use Dagger2 . In this library it is possible to assign a custom scope and then using
public class MyApp extends Application { ... }
You can create these objects with different lifetimes, for example, within one activity , or within several activities .
This model works well if you have one module. By module, I mean a module that creates android studio (each module has java files, resource files, a manifest file) ( Not a module that uses dagger2 , @Module ).
But I have a multi-module project:
Those. there is a common module Module1 , which, depending on the situation, connects either Module2 , or Module3 , or some other module.
The problem is that all modules must have access to the MyApp class in order to build an interface component and at the same time, the MyApp class must have a place for all modules.
For example, if MyApp is announced in Module1 then:
1) Component interface will be as follows
@Singleton @Component(modules = {NetworkApiModule.class}) public interface DiComponent { // to update the fields in your activities void inject(MainActivity2 activity); // }
MainActivity2 is a class announced in Module2, everything will work without problems.
2) Next, MyApp :
public class MyApp extends Application { DiComponent component; @Override public void onCreate() { super.onCreate(); component = DaggerDiComponent.builder().build(); } public DiComponent getComponent() { return component; }
}
Everything is also without problems.
3) Next we need to introduce dependencies for example in MainActivity2 which is in Module2 :
public class MainActivity2 extends Activity { @Inject NetworkApi networkApi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ((MyApp) getApplication()).getComponent().inject(this); } }
And here there is a problem how to get access to MyApp which is in Module1 , if MainActivity2 is in Module2 .
Those. in general, the class MyApp should be in some of the modules and it turns out in one direction we can provide access ( Module1-> Module2 ) and in the other no longer ( Module2-> Module1 ).
How to solve this problem? Is it possible in this case to do something?
Thank you in advance for all the answers.