How to Use Dragger Library in Android App?
Dagger is a framework for Android, Java, and Kotlin. Dagger is used to minimize the project complexity and you can remove all dependency injection or services locators in an Android app that can be a problem. Matic dependencies on the size of your project. Dagger automatically generates code that mimics the code. Let’s Know How Dagger Work.
Working of Dagger
Create a simple factory for the UserRepository class shown in the following diagram
UserLocalDataSource
/
/
/
/
UserResponsibility
\
\
\
\
UserRemoteDataSource
UserRepository as follows:
public class ThisIsUserRepository {
private final ThisIsUserLocalDataSource userLocalDataSource;
private final ThisIsUserRemoteDataSource userRemoteDataSource;
public UserRepository(ThisIsUserLocalDataSource userLocalDataSource, ThisIsUserResponsibility
this.userLocalDataSource = userLocalDataSource;
this.userRemoteDataSource = userRemoteDataSource;
}
}
How Dagger Works in Android
Let’s take an example Android App with the dependency graph
Local Activity
| UserLocalSource
| /
| /
Login ViewModel——>User Repository —–>UserRemoteDataSource
|
|
Retrofit
Basically What we do if we need to use Dagger in our application, we create a Dagger graph that lives in our application. An instance of the graph is available as long as the app is running. This is how the graph is attached to the app life cycle. One advantage of this approach is that graph is available to other android framework classes. This is simple Java code for this
public interface ThisIsApplicationComponent {
}
public class ThisIsMyApplication extends Application {
ThisIsApplicationComponent appComponent = ThisIsDaggerApplicationComponent.create();
}