As promised, part two is here. ? Before we get our hands dirty, let’s do a quick recap. In the previous post, we created a simple app that displays a list of user names using Android architecture components library. We divided our app into the following layers for better code responsibility and separation of concerns:
- View/UI layer
- ViewModel layer
This worked pretty well but our data was hard coded. In this series, we will setup Retrofit for API Calls & Dagger 2 to add Dependency Injection to our app and use TMDB API to get some data. With that said, our new architecture will look like below.
Picture from: Android developers site
Before We Begin …
Who the hell is Dagger and what is Dependency Injection? Worry not we will walk through this first. So let’s define some terms.
Dependency: This is when a class has a dependency on another class, if it uses an instance of this class. We call this a _class dependency.
Dependency Injection: Also known as DI. Dependency Injection is a technique whereby one object supplies the dependencies of another object. This means an object creating its dependendencies via
new operator is strictly prohibited.
We will be using Dagger 2 for DI.
Dagger 2 uses the following annotations:
@Provides: define classes and methods which provide dependencies.
@Inject: request dependencies. Can be used on a constructor, a field, or a method.
@Component: enable selected modules and used for performing dependency injection
@Singleton: annotation ensures the class instance as singleton across the dependency graph.
Dependency Injection can be a beast and I don’t want to dive into it. There are a couple of articles that talk about this. I’ll add them at the end of the article. ?
For some organization, We’ll handle injection in a package called
The source code is available on Github.
You’ll need to add dagger dependencies to your
We’ll set up a couple of module classes.
- App Module: This will ensure that
TmdbServicewill be a singleton throughout our app.
- NetworkModule: This helps us setup retrofit and logging.
- ViewModelModule: Module to set up our viewmodels.
Let’s set up our modules:
We’ve done a couple of things in the NetworkModule that I think are work taking note of
provideOkHttpInterceptors(): Sets up HTTP logging. This will allow us to monitor network requests and responses. It will only log when running the Debug version.
okHttpClient(): Sets up OkHttp client with some custom configs.e.g Adding HTTP logger, set timeout & read duration and custom interceptor that adds TMDB API key to requests.
provideRetrofitClient(): Sets up Retrofit client.
Now that we have the Network module created, we can create an app module that will now ensure we have a singleton for our API service interface. If you’ve not used Retrofit, the interface defines API endpoints. It simply looks like this.
Here’s how the NetworkModule looks like. We’ve added the NetworkModule and ViewModelModule to the AppModule.
The method names for the providers, such as
provideRetrofitClient(), are not important and can be named anything you like. Dagger only looks at the return type.
We only have one component at the moment
We’ve specified the modules we want to be used with the component inside the
Boom. We are done setting up our dagger. ?
Let The @Injection Begin
Now that we have all our dependencies set up, let’s use them.
1. Application Class
We need to initialize the dependency graph for our application by using the Component. This is pretty simple in Dagger 2.
Don’t forget to add property
android:name=".TmdbApp" to the tag in
2. TmdbRepository Class
I’ve created a class
TmdbRepository in the repository package that is responsible for making API requests and returning data to our ViewModels.
@Inject annotation on
TmdbRepository constructor which in turn tells Dagger that to use the constructor to create an instance of
TmdbService. This adds this class to the Dependency Graph.
3. MainActivityViewModel Class
As discussed earlier, using
@Inject annotation on
MainActivityViewModel constructor which in turn tells Dagger that to use the constructor to create an instance of
By doing so, the ViewModel does not care how we get out data. It just wants data from our repository.
4. ProjectViewModelFactory Class
ViewModelProvider.Factory. This class is responsible for instantiating our ViewModel classes.
5. MainActivity Class
We can now use load data in our MainActivity. We call
getPopularMovies() which will return some data. We then use
observe which will listen for any changes to our data.
This is how the entire code looks like.
Wrapping it up
You can download the final project on Github
Dagger can be a bit of a pain when starting but don’t let it get to you. Dependency injection becomes useful when implementing proper testing into your app, allowing mock implementations of back-end APIs and data repositories to be used in testing.
There’s much more to learn about in Dagger 2 and its usage, including:
- Testing with Mockito
In the next series, well look at setting up the UI and maybe writing some tests. In the meantime, happy injecting.
- Vogella – Dependency Injection
- YouTube video by Gregory Kick: DAGGER 2 – A New Type of dependency injection
- YouTube video on DI by Dan Lew: Dependency Injection made simple
- Dagger 2: official page
- Codepath: tutorial on Dagger 2