An Introduction to Dagger 2 (Android DI) – Part 2
Learn more about Dagger 2, this time focused on creating new components, classes, and more!
Join the DZone community and get the full member experience.
Join For FreeIn the previous article, we have a quick introduction to Dagger 2 with a simple introductory example. In this article, I will show you how to use Android Build variants with Dagger 2 to have different implementations (for the service interface) that are switched automatically when the app is in the debug mode or in the release mode.
First of all, under the release directory, let’s create a new component DaggerGraphComponent
which extends from DaggerGraph
as follows.
@Singleton
@Component(modules = {MainModule.class, ServiceModule.class})
public interface DaggerGraphComponent extends DaggerGraph {
static final class Initializer {
private Initializer() {
}
public static DaggerGraph init(DaggerApplication app) {
return DaggerDaggerGraphComponent.builder()
.mainModule(new MainModule(app))
.build();
}
}
}
Secondly, create a service module which will be responsible for creating the instances of HelloService
implementations (in debug and release modes).
For the release mode, ServiceModule
provides only an instance of the HelloServiceReleaseManager
class which implements HelloService
.
@Module
public class ServiceModule {
@Provides
@Singleton
HelloService provideHelloService() {
return new HelloServiceReleaseManager();
}
}
Below is HelloServiceReleaseManager
simple implementation.
public class HelloServiceReleaseManager implements HelloService {
@Override
public String greet(String userName) {
return "Hello " + userName + "! [Release]";
}
}
Apply the same steps under the debug directory, in debug case, you can have a HelloServiceDebugManager
class which implements HelloService
interface as shown below.
public class HelloServiceDebugManager implements HelloService {
@Override
public String greet(String userName) {
return "Hello " + userName + "! [Debug]";
}
}
Make sure to have the following code hierarchy in release and debug.
Running the project
Now, you can run the app in debug mode, and then enter some name and then click “Greet!” button, you will find the debug service response as follows.
And then change the build variant to run the app in the release mode and do the same previous steps to see the results as shown below.
Checkout the code
Check the sample app code in GitHub:
https://github.com/hazems/Dagger-Sample/tree/dagger-sample2
What is next?
So in the next article, I will discuss how can we apply unit testing techniques for Dagger 2 applications. Stay tuned!
Opinions expressed by DZone contributors are their own.
Comments