SlideShare a Scribd company logo
Dagger 2
INJEÇÃO DE DEPENDÊNCIA
Injecão de Dependência
 Dependência é qualquer objeto necessário
para o funcionamento de uma classe;
 Desacoplamento entre classes de alto e
baixo nível;
 Inexistente, manual ou automática.
public class ClassA {
private ClassB mClassB;
public ClassA() {
mClassB = new ClassB();
}
}
public class ClassA {
private ClassB mClassB;
public ClassA() {
mClassB = new ClassB(new ClassC());
}
}
public class ClassA {
private ClassB mClassB;
public ClassA(ClassB classB) {
mClassB = classB;
}
}
Bibliotecas
 Guice
 Dagger (v1)
 Dagger 2
 ...
Funcionamento
@Bind(R.id.home_iv) ImageView mImageView;
ButterKnife.bind(this, view);
view mImageView
findViewbyId
@Bind
mImageView = (ImageView)view.findViewbyId(R.id.home_iv);
Funcionamento
Component Object
“findObjectOfTypeX”
@Inject
Module
Exemplo
Retrofit
bit.ly/di-android-meetup
Retrofit Service
public class GitHubApi {
public static final int CACHE_SIZE = 5 * 1024 * 1024;
public static <S> S createService(Class<S> serviceClass, Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
final Gson gson = gsonBuilder.create();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.cache(new Cache(context.getCacheDir(), CACHE_SIZE))
.readTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(BuildConfig.API_URL)
.client(client)
.build();
return retrofit.create(serviceClass);
}
}
UserModel
public class GitHubUserModel {
private final GitHubService mService;
public GitHubUserModel(Context context) {
mService = GitHubApi.createService(GitHubService.class, context);
}
public Call<List<GitHubUser>> fetchUsers(int page) {
return mService.getUsers(page);
}
...
}
GitHubUserModel userModel = new GitHubUserModel(getActivity().getApplicationContext());
mActionInteractor = new UsersListPresenter(this, userModel);
mActionInteractor.loadUsersList(false);
Introduzindo Dagger
Dagger API
 @Module + @Provides
 Mecanismo para prover dependências
 @Inject
 Mecanismo para requisitar dependências
 @Component
 Ligação entre módulos e injeções
Dagger
Project/build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8’
}
}
App/build.gradle
apply plugin: 'com.neenbedankt.android-apt'
compile 'com.google.dagger:dagger:2.0.2'
apt 'com.google.dagger:dagger-compiler:2.0.2'
provided 'org.glassfish:javax.annotation:10.0-b28'
@Module
public class NetworkModule {
public static final int CACHE_SIZE = 5 * 1024 * 1024;
@Provides
public Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(BuildConfig.API_URL)
.client(client)
.build();
}
@Provides
public OkHttpClient provideHttpClient(HttpLoggingInterceptor interceptor, Cache cache) {
return new OkHttpClient.Builder()
.addInterceptor(interceptor)
.cache(cache)
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
}
@Provides
public Cache provideCache(Application application) {
return new Cache(application.getCacheDir(), CACHE_SIZE);
}
@Provides
public HttpLoggingInterceptor provideHttpInterceptor() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return interceptor;
}
@Provides
public Gson provideHttpGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
}
@Module
public class GitHubModule {
public interface GitHubService {
@GET("/users")
@Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN)
Call<List<GitHubUser>> getUsers();
@GET("/users/{login}")
@Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN)
Call<GitHubUser> getUser(@Path("login") String login);
@GET("/users")
@Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN)
Call<List<GitHubUser>> getUsers(@Query("since") int page);
}
@Provides
public GitHubService provideGitHubService(Retrofit retrofit) {
return retrofit.create(GitHubService.class);
}
}
@Module
public class AppModule {
private final Context mApplicationContext;
public AppModule(Context applicationContext) {
mApplicationContext = applicationContext;
}
@Provides
@PerApp
public Context provideApplicationContext() {
return mApplicationContext;
}
}
@Component(modules = {AppModule.class, GitHubModule.class, NetworkModule.class})
public interface AppComponent {
void inject(UsersListFragment fragment);
}
DepencyInjectionApplication.java
@NonNull
protected DaggerAppComponent.Builder prepareAppComponent() {
return DaggerAppComponent.builder()
.networkModule(new NetworkModule())
.gitHubModule(new GitHubModule())
.appModule(new AppModule(this));
}
GitHubUserModel.java
public class GitHubUserModel {
private final GitHubModule.GitHubService mService;
@Inject
public GitHubUserModel(GitHubModule.GitHubService service) {
mService = service;
}
...
}
UsersListFragment.java
@Inject public GitHubUserModel mUserModel;
@Override
protected void onCreate() {
DepencyInjectionApplication.getAppComponent(getActivity()).inject(this);
}
@Override
protected void onResume() {
mActionInteractor = new UsersListPresenter(this, mUserModel);
mActionInteractor.loadUsersList(false);
}
GitHubUserModel
Retrofit
OkHttpClient
Gson
NetworkModule#provideRetrofit
NetworkModule#provideHttpClient
NetworkModule#provideGson
GitHubService GitHubModule#provideGitHubService
Component Dependency
@Component(modules={AppModule.class, NetworkModule.class})
public interface NetComponent {
Retrofit retrofit();
}
@Component(dependencies = NetComponent.class, modules = GitHubModule.class)
public interface AppComponent {
void inject(UsersListFragment fragment);
}
public class DepencyInjectionApplication extends Application {
private AppComponent mAppComponent;
private NetComponent mNetComponent;
private void setupDaggerAppComponent() {
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
// .networkModule(new NetworkModule()) is free
.build();
mAppComponent = DaggerAppComponent.builder()
// .gitHubModule(new GitHubModule()) is free
.netComponent(mNetComponent)
.build();
}
}
Subcomponent
@Subcomponent(modules = GitHubModule.class)
public interface GitHubComponent {
void inject(UsersListFragment fragment);
}
@Component(modules = {NetworkModule.class, AppModule.class})
public interface AppComponent {
Application getApplication();
GitHubComponent plus(GitHubModule gitHubModule);
}
DepencyInjectionApplication.java
private void setupDaggerAppComponent() {
mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
UsersListFragment.java
@Override
protected void onCreate() {
DepencyInjectionApplication.getAppComponent(getActivity())
.plus(new GitHubModule())
.inject(this);
}
@Override
protected void onResume() {
mActionInteractor = new UsersListPresenter(this, mUserModel);
mActionInteractor.loadUsersList(false);
}
Scopes
 Determinam a intenção de duração de ciclo de vida de um
component;
 @Singleton é o único suportado out-of-the-box;
 Deve ser usado no nível de aplicação
 Custom scopes permitem maior flexibilidade, mas cabe
ao programador respeitar o ciclo de vida.
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerActivity {}
@Module
public class MyActivityModule {
@PerActivity
@Named("ActivityScope") @Provides
StringBuilder provideStringBuilderActivityScope() {
return new StringBuilder("Activity");
}
@Named("Unscoped") @Provides
StringBuilder provideStringBuilderUnscoped() {
return new StringBuilder("Unscoped");
}
}
public class MyActivity {
@Inject @Named("ActivityScope")
StringBuilder activityScope1;
@Inject @Named("ActivityScope")
StringBuilder activityScope2;
@Inject @Named("Unscoped")
StringBuilder unscoped1;
@Inject @Named("Unscoped")
StringBuilder unscoped2;
public void onCreate() {
activityScope1.append("123");
activityScope1.toString(); // output: "Activity123"
activityScope2.append("456");
activityScope2.toString(); // output: "Activity123456"
unscoped1.append("123");
unscoped1.toString(); // output: "Unscoped123"
unscoped2.append("456");
unscoped2.toString(); // output: "Unscoped456"
}
}
Bonus
 Lazy;
 Inicialização de Map e Set;
 Producer assíncrono;
Conclusão
 Fácil acesso à variáveis compartilhadas;
 Desacoplamento de dependências complexas;
 Controle de ciclo de vida;
 Performance.
Dúvidas?
edson-menegatti-87898718
3dm1
edson.menegatti.7
Referências
https://www.youtube.com/watch?v=oK_XtfXPkqw
https://github.com/codepath/android_guides/wiki/Dependenc
y-Injection-with-Dagger-2
https://www.parleys.com/tutorial/5471cdd1e4b065ebcfa1d55
7/
https://blog.gouline.net/2015/05/04/dagger-2-even-sharper-
less-square/
https://www.youtube.com/watch?v=SKFB8u0-VA0

More Related Content

PDF
Android development
PDF
Testing Android apps based on Dagger and RxJava
PDF
Testing Android apps based on Dagger and RxJava Droidcon UK
PPTX
Dependency Injection for Android
PPTX
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
PPTX
Sword fighting with Dagger GDG-NYC Jan 2016
PDF
Advanced Dagger talk from 360andev
PDF
Intro to Retrofit 2 and RxJava2
Android development
Testing Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJava Droidcon UK
Dependency Injection for Android
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Sword fighting with Dagger GDG-NYC Jan 2016
Advanced Dagger talk from 360andev
Intro to Retrofit 2 and RxJava2

What's hot (20)

PDF
My way to clean android v2 English DroidCon Spain
PPTX
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
PDF
My way to clean android V2
PPTX
Open sourcing the store
PDF
Thomas braun dependency-injection_with_robo_guice-presentation-final
PDF
Best Practices in Qt Quick/QML - Part III
 
PDF
Modern Android app library stack
PDF
Android architecture blueprints overview
PDF
Dagger 2. Right way to do Dependency Injection
PPTX
Dagger 2. The Right Way to Dependency Injections
PDF
Sharper Better Faster Dagger ‡ - Droidcon SF
PDF
Using hilt in a modularized project
PDF
Under the Hood: Using Spring in Grails
PDF
Under the Hood: Using Spring in Grails
PPTX
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
PDF
GKAC 2015 Apr. - RxAndroid
PDF
Introduction to Retrofit and RxJava
PDF
Best Practices in Qt Quick/QML - Part II
 
PDF
Automated%20testing%20with%20Espresso2.x
PDF
Best Practices in Qt Quick/QML - Part IV
 
My way to clean android v2 English DroidCon Spain
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
My way to clean android V2
Open sourcing the store
Thomas braun dependency-injection_with_robo_guice-presentation-final
Best Practices in Qt Quick/QML - Part III
 
Modern Android app library stack
Android architecture blueprints overview
Dagger 2. Right way to do Dependency Injection
Dagger 2. The Right Way to Dependency Injections
Sharper Better Faster Dagger ‡ - Droidcon SF
Using hilt in a modularized project
Under the Hood: Using Spring in Grails
Under the Hood: Using Spring in Grails
【Potatotips #26】Replace EventBus with RxJava/RxAndroid
GKAC 2015 Apr. - RxAndroid
Introduction to Retrofit and RxJava
Best Practices in Qt Quick/QML - Part II
 
Automated%20testing%20with%20Espresso2.x
Best Practices in Qt Quick/QML - Part IV
 
Ad

Viewers also liked (11)

PPTX
Umbraco Introduction
PDF
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
DOCX
5126 5130.output
PDF
Andef manual boas_praticas_agricolas_web_081013192330
DOCX
5141 5145.output
PPT
geo 202 shale gas
PDF
About Shared Value Initiative India
PPTX
Multiple sclerosis
PPTX
Trabalho de fundamentos e metod. lingua portuguesa
PDF
Dagger 2
PDF
BREEAM and Environmental Assessment Methods Amanda Gallagher EASLAR
Umbraco Introduction
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
5126 5130.output
Andef manual boas_praticas_agricolas_web_081013192330
5141 5145.output
geo 202 shale gas
About Shared Value Initiative India
Multiple sclerosis
Trabalho de fundamentos e metod. lingua portuguesa
Dagger 2
BREEAM and Environmental Assessment Methods Amanda Gallagher EASLAR
Ad

Similar to Dagger 2 - Injeção de Dependência (20)

PDF
Overview of Android Infrastructure
PDF
Overview of Android Infrastructure
PDF
Enterprise Guice 20090217 Bejug
PPTX
Dependency injection using dagger2
PDF
Singletons in PHP - Why they are bad and how you can eliminate them from your...
PPTX
Android architecture
PDF
Architecting your GWT applications with GWT-Platform - Lesson 02
KEY
Android Bootstrap
PDF
Powerful persistence layer with Google Guice & MyBatis
PDF
Idiomatic Gradle Plugin Writing
ODP
Codemotion appengine
PDF
Improving android experience for both users and developers
PDF
Droidcon2013 android experience lahoda
PDF
Why Spring <3 Kotlin
PPTX
Android getting started
PDF
Workshop 26: React Native - The Native Side
PDF
Dependency injection crash course
PPTX
Functions and Objects in JavaScript
KEY
CDI e as ideias pro futuro do VRaptor
PDF
droidparts
Overview of Android Infrastructure
Overview of Android Infrastructure
Enterprise Guice 20090217 Bejug
Dependency injection using dagger2
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Android architecture
Architecting your GWT applications with GWT-Platform - Lesson 02
Android Bootstrap
Powerful persistence layer with Google Guice & MyBatis
Idiomatic Gradle Plugin Writing
Codemotion appengine
Improving android experience for both users and developers
Droidcon2013 android experience lahoda
Why Spring <3 Kotlin
Android getting started
Workshop 26: React Native - The Native Side
Dependency injection crash course
Functions and Objects in JavaScript
CDI e as ideias pro futuro do VRaptor
droidparts

Recently uploaded (20)

PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Introduction to Artificial Intelligence
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
AI in Product Development-omnex systems
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
System and Network Administraation Chapter 3
PDF
top salesforce developer skills in 2025.pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
L1 - Introduction to python Backend.pptx
PDF
Odoo Companies in India – Driving Business Transformation.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Design an Analysis of Algorithms II-SECS-1021-03
Adobe Illustrator 28.6 Crack My Vision of Vector Design
ManageIQ - Sprint 268 Review - Slide Deck
Wondershare Filmora 15 Crack With Activation Key [2025
Introduction to Artificial Intelligence
Understanding Forklifts - TECH EHS Solution
Internet Downloader Manager (IDM) Crack 6.42 Build 41
How to Migrate SBCGlobal Email to Yahoo Easily
AI in Product Development-omnex systems
Upgrade and Innovation Strategies for SAP ERP Customers
System and Network Administraation Chapter 3
top salesforce developer skills in 2025.pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
VVF-Customer-Presentation2025-Ver1.9.pptx
ISO 45001 Occupational Health and Safety Management System
Softaken Excel to vCard Converter Software.pdf
Design an Analysis of Algorithms I-SECS-1021-03
L1 - Introduction to python Backend.pptx
Odoo Companies in India – Driving Business Transformation.pdf

Dagger 2 - Injeção de Dependência

  • 1. Dagger 2 INJEÇÃO DE DEPENDÊNCIA
  • 2. Injecão de Dependência  Dependência é qualquer objeto necessário para o funcionamento de uma classe;  Desacoplamento entre classes de alto e baixo nível;  Inexistente, manual ou automática.
  • 3. public class ClassA { private ClassB mClassB; public ClassA() { mClassB = new ClassB(); } }
  • 4. public class ClassA { private ClassB mClassB; public ClassA() { mClassB = new ClassB(new ClassC()); } }
  • 5. public class ClassA { private ClassB mClassB; public ClassA(ClassB classB) { mClassB = classB; } }
  • 6. Bibliotecas  Guice  Dagger (v1)  Dagger 2  ...
  • 7. Funcionamento @Bind(R.id.home_iv) ImageView mImageView; ButterKnife.bind(this, view); view mImageView findViewbyId @Bind mImageView = (ImageView)view.findViewbyId(R.id.home_iv);
  • 10. Retrofit Service public class GitHubApi { public static final int CACHE_SIZE = 5 * 1024 * 1024; public static <S> S createService(Class<S> serviceClass, Context context) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); final Gson gson = gsonBuilder.create(); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor) .cache(new Cache(context.getCacheDir(), CACHE_SIZE)) .readTimeout(30, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS) .build(); Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(BuildConfig.API_URL) .client(client) .build(); return retrofit.create(serviceClass); } }
  • 11. UserModel public class GitHubUserModel { private final GitHubService mService; public GitHubUserModel(Context context) { mService = GitHubApi.createService(GitHubService.class, context); } public Call<List<GitHubUser>> fetchUsers(int page) { return mService.getUsers(page); } ... } GitHubUserModel userModel = new GitHubUserModel(getActivity().getApplicationContext()); mActionInteractor = new UsersListPresenter(this, userModel); mActionInteractor.loadUsersList(false);
  • 13. Dagger API  @Module + @Provides  Mecanismo para prover dependências  @Inject  Mecanismo para requisitar dependências  @Component  Ligação entre módulos e injeções
  • 14. Dagger Project/build.gradle buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.5.0' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8’ } } App/build.gradle apply plugin: 'com.neenbedankt.android-apt' compile 'com.google.dagger:dagger:2.0.2' apt 'com.google.dagger:dagger-compiler:2.0.2' provided 'org.glassfish:javax.annotation:10.0-b28'
  • 15. @Module public class NetworkModule { public static final int CACHE_SIZE = 5 * 1024 * 1024; @Provides public Retrofit provideRetrofit(Gson gson, OkHttpClient client) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(BuildConfig.API_URL) .client(client) .build(); } @Provides public OkHttpClient provideHttpClient(HttpLoggingInterceptor interceptor, Cache cache) { return new OkHttpClient.Builder() .addInterceptor(interceptor) .cache(cache) .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .build(); } @Provides public Cache provideCache(Application application) { return new Cache(application.getCacheDir(), CACHE_SIZE); } @Provides public HttpLoggingInterceptor provideHttpInterceptor() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return interceptor; } @Provides public Gson provideHttpGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create(); } }
  • 16. @Module public class GitHubModule { public interface GitHubService { @GET("/users") @Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN) Call<List<GitHubUser>> getUsers(); @GET("/users/{login}") @Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN) Call<GitHubUser> getUser(@Path("login") String login); @GET("/users") @Headers("Authorization: token " + BuildConfig.GITHUB_TOKEN) Call<List<GitHubUser>> getUsers(@Query("since") int page); } @Provides public GitHubService provideGitHubService(Retrofit retrofit) { return retrofit.create(GitHubService.class); } }
  • 17. @Module public class AppModule { private final Context mApplicationContext; public AppModule(Context applicationContext) { mApplicationContext = applicationContext; } @Provides @PerApp public Context provideApplicationContext() { return mApplicationContext; } }
  • 18. @Component(modules = {AppModule.class, GitHubModule.class, NetworkModule.class}) public interface AppComponent { void inject(UsersListFragment fragment); } DepencyInjectionApplication.java @NonNull protected DaggerAppComponent.Builder prepareAppComponent() { return DaggerAppComponent.builder() .networkModule(new NetworkModule()) .gitHubModule(new GitHubModule()) .appModule(new AppModule(this)); }
  • 19. GitHubUserModel.java public class GitHubUserModel { private final GitHubModule.GitHubService mService; @Inject public GitHubUserModel(GitHubModule.GitHubService service) { mService = service; } ... } UsersListFragment.java @Inject public GitHubUserModel mUserModel; @Override protected void onCreate() { DepencyInjectionApplication.getAppComponent(getActivity()).inject(this); } @Override protected void onResume() { mActionInteractor = new UsersListPresenter(this, mUserModel); mActionInteractor.loadUsersList(false); }
  • 22. @Component(modules={AppModule.class, NetworkModule.class}) public interface NetComponent { Retrofit retrofit(); } @Component(dependencies = NetComponent.class, modules = GitHubModule.class) public interface AppComponent { void inject(UsersListFragment fragment); } public class DepencyInjectionApplication extends Application { private AppComponent mAppComponent; private NetComponent mNetComponent; private void setupDaggerAppComponent() { mNetComponent = DaggerNetComponent.builder() .appModule(new AppModule(this)) // .networkModule(new NetworkModule()) is free .build(); mAppComponent = DaggerAppComponent.builder() // .gitHubModule(new GitHubModule()) is free .netComponent(mNetComponent) .build(); } }
  • 24. @Subcomponent(modules = GitHubModule.class) public interface GitHubComponent { void inject(UsersListFragment fragment); } @Component(modules = {NetworkModule.class, AppModule.class}) public interface AppComponent { Application getApplication(); GitHubComponent plus(GitHubModule gitHubModule); } DepencyInjectionApplication.java private void setupDaggerAppComponent() { mAppComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); } UsersListFragment.java @Override protected void onCreate() { DepencyInjectionApplication.getAppComponent(getActivity()) .plus(new GitHubModule()) .inject(this); } @Override protected void onResume() { mActionInteractor = new UsersListPresenter(this, mUserModel); mActionInteractor.loadUsersList(false); }
  • 25. Scopes  Determinam a intenção de duração de ciclo de vida de um component;  @Singleton é o único suportado out-of-the-box;  Deve ser usado no nível de aplicação  Custom scopes permitem maior flexibilidade, mas cabe ao programador respeitar o ciclo de vida.
  • 26. @Scope @Retention(RetentionPolicy.RUNTIME) public @interface PerActivity {} @Module public class MyActivityModule { @PerActivity @Named("ActivityScope") @Provides StringBuilder provideStringBuilderActivityScope() { return new StringBuilder("Activity"); } @Named("Unscoped") @Provides StringBuilder provideStringBuilderUnscoped() { return new StringBuilder("Unscoped"); } }
  • 27. public class MyActivity { @Inject @Named("ActivityScope") StringBuilder activityScope1; @Inject @Named("ActivityScope") StringBuilder activityScope2; @Inject @Named("Unscoped") StringBuilder unscoped1; @Inject @Named("Unscoped") StringBuilder unscoped2; public void onCreate() { activityScope1.append("123"); activityScope1.toString(); // output: "Activity123" activityScope2.append("456"); activityScope2.toString(); // output: "Activity123456" unscoped1.append("123"); unscoped1.toString(); // output: "Unscoped123" unscoped2.append("456"); unscoped2.toString(); // output: "Unscoped456" } }
  • 28. Bonus  Lazy;  Inicialização de Map e Set;  Producer assíncrono;
  • 29. Conclusão  Fácil acesso à variáveis compartilhadas;  Desacoplamento de dependências complexas;  Controle de ciclo de vida;  Performance.