To learn Dagger 2, I decided to rewrite my application, but I was stuck in finding the right solution for the next problem.
For this example, suppose we have an interface named Mode :
public interface Mode { Object1 obj1();
and two implementations: NormalMode and DemoMode .
The mode is stored in singleton mode, so it can be accessed from anywhere in the application.
public enum ModeManager { INSTANCE,; private Mode mode; public Mode mode() { if (mode == null) mode = new NormalMode(); return mode; } public void mode(Mode mode) {
NormalMode switches to DemoMode at runtime (say when the user clicks several times in the background)
public void backgroundClicked5Times(){ ModeManager.INSTANCE.mode(new DemoMode());
So, first I got rid of the singleton and defined the modes as Dagger 2 modules:
@Module public class NormalModeModule { @Provides public Object1 provideObject1() { return new NormalObject1(); } } @Module public class DemoModeModule { @Provides public Object1 provideObject1() { return new DemoObject1(); } }
Now in the backgroundClicked5Times method, instead of dealing with singleton, I would like to replace NormalModeModule with DemoModeModule in the DAG so that other classes that need Object1 get the implementation of DemoObject1 from now on.
How can I do this in a dagger?
Thanks in advance.
dependency-injection dagger-2
Marcin
source share