Reputation: 1238
The Background:
I'm using Dagger2
for dependency injection in my Android
app and I want to inject an object as a singleton into my BaseActivity to be available throughout the whole app, but the value of the Object can only be set after an authentication process and its value depends on the outcome of the authentication.
The Build:
This is what my current setup looks like:
public interface Tool {
...
}
public class ToolOne implements Tool {
...
}
public class ToolTwo implements Tool {
...
}
A general interface and two different implementations of it.
public class ToolConfig {
private Tool currentTool;
public ToolConfig(Tool tool) {
this.currentTool = tool;
}
...
}
A class that functions as configuration and is used throughout the whole app.
@Provides
@PerApplication
ToolConfig provideToolConfig(Tool tool) {
return new ToolConfig(tool);
}
The way the configuration is defined in my ToolModule for Dagger. This will be injected into the BaseActivity to be available for all classes.
The task:
How can I set the value of currentTool
for the configuration? Depending on the authentication process, either ToolOne
or ToolTwo
should be set as value of currentTool
. It should be possible to change it if the authentication process is done again. This will rarely be the case after it was set once, but it could happen and I want to be sure to always use the same instance of the object.
Is there a recommended way how I could do this with Dagger2?
Upvotes: 2
Views: 1473
Reputation: 95654
You can just define a @Provides
method that redirects between them:
@Provides Tool provideTool(
AuthenticationController authController,
Provider<ToolOne> toolOneProvider,
Provider<ToolTwo> toolTwoProvider) {
if (authController.useToolTwo()) {
return toolTwoProvider.get();
}
return toolOneProvider.get();
}
However, in a case like that, you'll need to be very careful to only inject a Provider<Tool>
(which will check AuthController every time you call get
) and not Tool
(which will check AuthController once when the Tool
-injected class is created but will not auto-update). For this reason it may make sense to create a custom one-method ToolProvider, where you inject the three deps as needed in the @Provides method and return the current tool as a getCurrentTool
call (etc).
Upvotes: 3