Dependency Injection
Dependency injection is a common design pattern used to overcome the dependency of one object to other like we always have some sort of dependency of an object, so dependency injection is used to supply dependencies to class and it is highly reusable which can further be used in other classes too.
Basically, this tutorial is a brief overview of dagger 2 framework for dependency injection, using the common annotation like @Module,@Inject,@Component i.e how to create a module, creating interfaces as components and Injection for creating an object.
Let's see the Implementation:
Every app has some form of dependency, so to remove the boilerplate that comes with the app we use Dagger 2. Dagger 2 is a well designed framework to remove the hard dependency and enables the object to create outside the class and used multiple times in app.
Common Annotations used by dagger2
- @Module
- @Component
- @Inject
- @provides
Every application has some form of dependency like using Facebook has a dependency on Facebook API and Facebook API has a dependency on Httpclient to call the API.
Annotations:
- @Module with @provides gives the mechanism for providing the dependency. A module is a class, whose methods provide dependency, therefore @Modules used on class and @provides used on methods.
- @Inject: used for request dependency.
- @Component: bridge between modules and injections
//@module oon class
@Module
public class NetworkModule{
//@provides on method
@Provides
OkHttpClient providesOkHttpClient(){
return new OkhttpClient();
}
@Provides
TwitterApi providesTwitterApi(OkhttpClient client){
return new TwitterApi(client);
}
}
In above module
-NetworkModule provides OkhttpCleint
-NetworkModule provides TwitterApi.
Now about Annotation Component which is bridge b/w module and injection, module here is Network Module
//@Component is bridge b/w injector and module
@Singleton //used for singleton pattern throughout the app
@Component(module=NetworkModule.class)
public interface APiComponent{
Twitter api();
}
@Inject for instantiating objects
public class TwitterApi{
OkhttpClient client;
// for creating object @Inject is must
@Inject
public TwitterApi(OkHttpClient client){
this.client=client;
}
public void postTweet(String user){
client.newCall(request).execute();
}
}
Hope you like the blog. Feel free to share your questions and feedback in the comment section below.
0 Comment(s)