SlideShare une entreprise Scribd logo
1  sur  31
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

Contenu connexe

Tendances

Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-final
Droidcon Berlin
 
Android application model
Android application modelAndroid application model
Android application model
magicshui
 
Automated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.xAutomated%20testing%20with%20Espresso2.x
Automated%20testing%20with%20Espresso2.x
Tatsuya Maki
 

Tendances (20)

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

En vedette

5126 5130.output
5126 5130.output5126 5130.output
5126 5130.output
j1075017
 
5141 5145.output
5141 5145.output5141 5145.output
5141 5145.output
j1075017
 

En vedette (11)

Umbraco Introduction
Umbraco IntroductionUmbraco Introduction
Umbraco Introduction
 
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
BUILD UPON: Riikka Holopainen - Lähes nollaenergiatason korjauksen esteet ja...
 
5126 5130.output
5126 5130.output5126 5130.output
5126 5130.output
 
Andef manual boas_praticas_agricolas_web_081013192330
Andef manual boas_praticas_agricolas_web_081013192330Andef manual boas_praticas_agricolas_web_081013192330
Andef manual boas_praticas_agricolas_web_081013192330
 
5141 5145.output
5141 5145.output5141 5145.output
5141 5145.output
 
geo 202 shale gas
geo 202 shale gasgeo 202 shale gas
geo 202 shale gas
 
About Shared Value Initiative India
About Shared Value Initiative IndiaAbout Shared Value Initiative India
About Shared Value Initiative India
 
Multiple sclerosis
Multiple sclerosisMultiple sclerosis
Multiple sclerosis
 
Trabalho de fundamentos e metod. lingua portuguesa
Trabalho de fundamentos e metod. lingua portuguesaTrabalho de fundamentos e metod. lingua portuguesa
Trabalho de fundamentos e metod. lingua portuguesa
 
Dagger 2
Dagger 2Dagger 2
Dagger 2
 
BREEAM and Environmental Assessment Methods Amanda Gallagher EASLAR
BREEAM  and Environmental Assessment Methods Amanda Gallagher EASLARBREEAM  and Environmental Assessment Methods Amanda Gallagher EASLAR
BREEAM and Environmental Assessment Methods Amanda Gallagher EASLAR
 

Similaire à Dagger 2 - Injeção de Dependência

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
robbiev
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatis
simonetripodi
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
Droidcon Berlin
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 

Similaire à Dagger 2 - Injeção de Dependência (20)

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

Dernier

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Dernier (20)

WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.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.