├── .editorconfig ├── .github └── workflows │ └── build.yml ├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── jraska │ │ └── dagger │ │ └── codelab │ │ └── app │ │ ├── FakeEventAnalytics.kt │ │ ├── TestDaggerApp.kt │ │ ├── TestRunner.kt │ │ └── test │ │ └── AppTest.kt │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── jraska │ │ └── dagger │ │ └── codelab │ │ └── app │ │ ├── DaggerApp.kt │ │ ├── PackageName.kt │ │ ├── di │ │ └── AppComponent.kt │ │ └── ui │ │ ├── MainActivity.kt │ │ └── MainFragment.kt │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ ├── activity_main.xml │ ├── content_main.xml │ └── fragment_main.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── core ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── jraska │ │ └── dagger │ │ └── codelab │ │ └── core │ │ ├── analytics │ │ ├── AnalyticsEvent.kt │ │ ├── AnalyticsFilter.kt │ │ ├── EventAnalytics.kt │ │ ├── LibraryEventAnalytics.kt │ │ ├── di │ │ │ ├── Analytics.kt │ │ │ ├── AnalyticsComponent.kt │ │ │ └── AnalyticsModule.kt │ │ └── lib │ │ │ └── AnalyticsLibrary.kt │ │ ├── app │ │ └── OnAppCreate.kt │ │ ├── config │ │ └── RemoteConfig.kt │ │ └── di │ │ └── HasAppComponent.kt │ └── test │ └── java │ └── com │ └── jraska │ └── dagger │ └── codelab │ └── core │ └── analytics │ └── AnalyticsComponentTest.kt ├── feature └── config │ ├── build.gradle │ └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── jraska │ │ └── dagger │ │ └── codelab │ │ └── config │ │ ├── ConfigTestApp.kt │ │ ├── ConfigTestRunner.kt │ │ └── test │ │ └── ConfigTest.kt │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── jraska │ └── dagger │ └── codelab │ └── config │ ├── ExpensiveConfig.kt │ ├── InMemoryConfig.kt │ ├── MultibindInMemoryConfig.kt │ ├── MutableConfig.kt │ ├── di │ ├── ConfigComponent.kt │ └── ConfigModule.kt │ └── ui │ └── ConfigActivity.kt ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | indent_style = space 8 | indent_size = 2 9 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: [push] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Checkout the code 8 | uses: actions/checkout@v2 9 | - name: Run Tests 10 | run: ./gradlew check --stacktrace 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated files 2 | bin/ 3 | gen/ 4 | 5 | # Gradle files 6 | .gradle/ 7 | build/ 8 | 9 | # Local configuration file (sdk path, etc) 10 | local.properties 11 | 12 | # Proguard folder generated by Eclipse 13 | proguard/ 14 | 15 | # Log Files 16 | *.log 17 | 18 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio 19 | 20 | *.iml 21 | 22 | # Directory-based project format: 23 | .idea/ 24 | # if you remove the above rule, at least ignore the following: 25 | 26 | # User-specific stuff: 27 | # .idea/workspace.xml 28 | # .idea/tasks.xml 29 | # .idea/dictionaries 30 | 31 | # Sensitive or high-churn files: 32 | # .idea/dataSources.ids 33 | # .idea/dataSources.xml 34 | # .idea/sqlDataSources.xml 35 | # .idea/dynamic.xml 36 | # .idea/uiDesigner.xml 37 | 38 | # Gradle: 39 | # .idea/gradle.xml 40 | # .idea/libraries 41 | 42 | # Mongo Explorer plugin: 43 | # .idea/mongoSettings.xml 44 | 45 | ## File-based project format: 46 | *.ipr 47 | *.iws 48 | 49 | ## Plugin-specific files: 50 | 51 | # IntelliJ 52 | /out/ 53 | 54 | # mpeltonen/sbt-idea plugin 55 | .idea_modules/ 56 | 57 | # JIRA plugin 58 | atlassian-ide-plugin.xml 59 | 60 | # Crashlytics plugin (for Android Studio and IntelliJ) 61 | com_crashlytics_export_strings.xml 62 | crashlytics.properties 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Dagger-Codelab 3 | Codelab to teach and demonstrate usage of dependency injection with Dagger 2 4 | 5 | [![CircleCI](https://circleci.com/gh/jraska/Dagger-Codelab.svg?style=svg)](https://circleci.com/gh/jraska/Dagger-Codelab) 6 | 7 | # What you will learn 8 | - About dependency injection(DI) and Inversion of Control(IoC) 9 | - Introduction to the problem, why it matters. 10 | - Why we use DI frameworks - which problems they solve for us. 11 | - Brief history of DI. Spring -> Guice -> Dagger 1 -> **Dagger 2** 12 | [Initial presentation slides](https://docs.google.com/presentation/d/1Yy6BdGQiZ8QQfT11Emwxs2F_bjAH4m9A8Ayz4luV2dw/edit?usp=sharing) 13 | - Basics of Dagger 14 | - How to setup Dagger in your project. 15 | - How to use `@Inject` annotation, creating simple `@Component` 16 | - Adding `@Module`. Discussion when to use modules and when `@Inject` annotation. 17 | - Usage of simple `@Singleton` scope. 18 | - Exploring Dagger generated source code and learning from it. 19 | - Wiring together with Android 20 | - Where to create and hold instances of components. 21 | - Injecting Activities, Injecting Fragments. 22 | - Using `@BindsInstance` to bind objects we don't own. 23 | - Multi-module project setup 24 | - How to compose modules together within `AppComponent` 25 | - Injecting Activity/Fragment and other dependencies within separate module. 26 | - Sharing instances with other modules. 27 | - Multibindings 28 | - Composing `@IntoMap` and `@IntoSet`. 29 | - Plugin based development within multi-module project. 30 | - Discuss which problems can multibinding solve. 31 | - Instrumented Testing 32 | - How to replace dependencies within `androidTest`. 33 | - Using separate component to replace dependencies in tests. 34 | - How to assert on your analytic events. 35 | - Dagger Hilt migration 36 | - Setting up Dagger Hilt in the project. 37 | - How to Migrate project to Hilt 38 | - Instrumented testing with Dagger Hilt 39 | - Setting up testing in project. 40 | - Replacing dependencies in tests 41 | - Discussing Hilt pros and cons. 42 | 43 | # Why this codelab? 44 | - Primarily this should be a learning resource for any engineer who wants to learn or recap Dagger usage. 45 | - The codelab format is chosen with the belief, that first hand experience leaves stronger memories and the skills are truly learned. 46 | - Dagger became more complex over years - making onboarding of new engineers harder. 47 | - Dagger became also misused or overused. New engineers see already brownfield and Dagger seems like one of the devils responsible for this leading to lower trust in the tool. Dagger can be almost invisible in your project. 48 | - We already forgot about the problems we had before Dagger like runtime DI resolution. It is important to be reminded about these problems. 49 | 50 | # How to use this Codelab 51 | - Codelab is split into few smaller sections - each of them can be run independently. 52 | - Each section has a branch with a format `{section number}-{area of focus}` e.g. `01-basics`. The branch with higher number is always the solution of the previous section. `master` branch is the final solution of present tasks. 53 | - You can run the codelab yourself, by following the instructions within each sections. 54 | - In case of any question, please feel free to [create an issue](https://github.com/jraska/Dagger-Codelab/issues/new) in this repo. 55 | 56 | ## Now let' start by moving to section you want 57 | - **[01-basics](https://github.com/jraska/Dagger-Codelab/tree/01-basics)** 58 | - **[02-wiring-with-android](https://github.com/jraska/Dagger-Codelab/tree/02-wiring-with-android)** 59 | - **[03-multiple-module-setup](https://github.com/jraska/Dagger-Codelab/tree/03-multiple-module-setup)** 60 | - **[04-multibindings](https://github.com/jraska/Dagger-Codelab/tree/04-multibindings)** 61 | - **[05-testing](https://github.com/jraska/Dagger-Codelab/tree/05-testing)** 62 | 63 | #### Dagger Hilt Option 64 | If you would like to see how would the current project look like in Dagger Hilt check the extra exercises: 65 | - **[06a-hilt-option-migration](https://github.com/jraska/Dagger-Codelab/tree/06a-hilt-option-migration)** 66 | - **[07a-hilt-option-testing](https://github.com/jraska/Dagger-Codelab/tree/07a-hilt-option-testing)** 67 | 68 | With solution at [08a-hilt-option-solution](https://github.com/jraska/Dagger-Codelab/tree/08a-hilt-option-solution) 69 | 70 | # References 71 | - [Android docs](https://developer.android.com/training/dependency-injection/dagger-basics), 72 | - [Multi-Module setup](https://developer.android.com/training/dependency-injection/dagger-multi-module) 73 | - [Google Codelab](https://codelabs.developers.google.com/codelabs/android-dagger) 74 | - [Dagger docs](https://dagger.dev) 75 | - [Android setup](https://dagger.dev/android) explains why we use field injection. 76 | - [Official tutorial](https://dagger.dev/tutorial/) 77 | - [Multibindings](https://dagger.dev/multibindings.html) 78 | - [`@Binds`/`@Provides` discussion](https://dagger.dev/faq.html#what-do-i-do-instead) 79 | - [Dagger Hilt](https://dagger.dev/hilt/) 80 | - [Hilt components](https://dagger.dev/hilt/components) 81 | - [Hilt Testing Philosophy](https://dagger.dev/hilt/testing-philosophy) 82 | - [Square - Anvil](https://github.com/square/anvil) Kotlin compiler plugin to automatically generate components for the applcation modules. 83 | - [Gregory Kick - DAGGER 2 - A New Type of dependency injection (2014)](https://www.youtube.com/watch?v=oK_XtfXPkqw) - Recommended resource to understand the history of DI and why Dagger 2 exists. 84 | - [Gregory Kick - Dagger to on MCE^3 (2016)](https://www.youtube.com/watch?v=iwjXqRlEevg) - Introduction of main Dagger features as we know them now like Multibindings and the rationale behind them. 85 | - [Josef Raska - 3 Years of Happy Marriage With Dagger 2 (2018)](https://proandroiddev.com/3-years-of-happy-marriage-with-dagger-2-b1e1e0febaa7) - Recap of which problems Dagger solved and how it moved Android development forward, even if it might not seem obvious now. 86 | - [Jake Wharton - Helping Dagger help you (2018)](https://jakewharton.com/helping-dagger-help-you/) - Showcase how far you can go with Dagger features and improvements. 87 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-kapt' 4 | 5 | android { 6 | compileSdkVersion 31 7 | 8 | defaultConfig { 9 | applicationId "com.jraska.dagger.codelab.app" 10 | minSdkVersion 24 11 | targetSdkVersion 31 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | testInstrumentationRunner "com.jraska.dagger.codelab.app.TestRunner" 16 | } 17 | } 18 | 19 | dependencies { 20 | implementation project(':core') 21 | implementation project(':feature:config') 22 | 23 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 24 | 25 | implementation 'com.google.dagger:dagger:2.43.1' 26 | kapt 'com.google.dagger:dagger-compiler:2.43.1' 27 | 28 | implementation 'androidx.appcompat:appcompat:1.4.2' 29 | implementation 'androidx.cardview:cardview:1.0.0' 30 | implementation 'androidx.lifecycle:lifecycle-runtime:2.5.1' 31 | implementation 'com.google.android.material:material:1.6.1' 32 | 33 | testImplementation 'junit:junit:4.13.2' 34 | 35 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 36 | androidTestImplementation 'androidx.test:runner:1.4.0' 37 | androidTestImplementation 'androidx.test:rules:1.4.0' 38 | 39 | kaptAndroidTest 'com.google.dagger:dagger-compiler:2.43.1' 40 | } 41 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/jraska/dagger/codelab/app/FakeEventAnalytics.kt: -------------------------------------------------------------------------------- 1 | package com.jraska.dagger.codelab.app 2 | 3 | import com.jraska.dagger.codelab.core.analytics.AnalyticsEvent 4 | import com.jraska.dagger.codelab.core.analytics.EventAnalytics 5 | 6 | class FakeEventAnalytics : EventAnalytics { 7 | val reportedAnalytics = mutableListOf() 8 | 9 | override fun reportEvent(event: AnalyticsEvent) { 10 | reportedAnalytics.add(event) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/jraska/dagger/codelab/app/TestDaggerApp.kt: -------------------------------------------------------------------------------- 1 | package com.jraska.dagger.codelab.app 2 | 3 | import android.content.Context 4 | import androidx.test.rule.ActivityTestRule 5 | import com.jraska.dagger.codelab.app.di.AppComponent 6 | import com.jraska.dagger.codelab.config.di.ConfigModule 7 | import com.jraska.dagger.codelab.core.analytics.AnalyticsEvent 8 | import com.jraska.dagger.codelab.core.analytics.EventAnalytics 9 | import dagger.BindsInstance 10 | import dagger.Component 11 | import dagger.Module 12 | import dagger.Provides 13 | import javax.inject.Singleton 14 | 15 | class TestDaggerApp : DaggerApp() { 16 | val fakeAnalytics = (appComponent() as TestAppComponent).fakeEventAnalytics() 17 | 18 | override fun createDaggerComponent(): AppComponent { 19 | return DaggerTestAppComponent.factory().create(this) 20 | } 21 | } 22 | 23 | fun ActivityTestRule<*>.reportedAnalytics(): List { 24 | return (activity.application as TestDaggerApp).fakeAnalytics.reportedAnalytics 25 | } 26 | 27 | @Singleton 28 | @Component(modules = [ConfigModule::class, FakeAnalyticsModule::class]) 29 | interface TestAppComponent : AppComponent { 30 | fun fakeEventAnalytics(): FakeEventAnalytics 31 | 32 | @Component.Factory 33 | interface Factory { 34 | fun create(@BindsInstance context: Context): TestAppComponent 35 | } 36 | } 37 | 38 | @Module 39 | object FakeAnalyticsModule { 40 | 41 | @Provides 42 | @Singleton 43 | fun fakeEventAnalytics(): FakeEventAnalytics = FakeEventAnalytics() 44 | 45 | @Provides 46 | fun eventAnalytics(fakeEventAnalytics: FakeEventAnalytics): EventAnalytics = fakeEventAnalytics 47 | } 48 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/jraska/dagger/codelab/app/TestRunner.kt: -------------------------------------------------------------------------------- 1 | package com.jraska.dagger.codelab.app 2 | 3 | import android.app.Application 4 | import android.content.Context 5 | import androidx.test.runner.AndroidJUnitRunner 6 | 7 | @Suppress("unused") // used in build.gradle 8 | class TestRunner : AndroidJUnitRunner() { 9 | override fun newApplication(cl: ClassLoader, className: String, context: Context): Application { 10 | return super.newApplication(cl, TestDaggerApp::class.qualifiedName, context) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/jraska/dagger/codelab/app/test/AppTest.kt: -------------------------------------------------------------------------------- 1 | package com.jraska.dagger.codelab.app.test 2 | 3 | import androidx.test.espresso.Espresso.onView 4 | import androidx.test.espresso.Espresso.pressBack 5 | import androidx.test.espresso.action.ViewActions.click 6 | import androidx.test.espresso.assertion.ViewAssertions.matches 7 | import androidx.test.espresso.matcher.ViewMatchers.isDisplayed 8 | import androidx.test.espresso.matcher.ViewMatchers.withId 9 | import androidx.test.espresso.matcher.ViewMatchers.withText 10 | import androidx.test.rule.ActivityTestRule 11 | import com.jraska.dagger.codelab.app.R 12 | import com.jraska.dagger.codelab.app.reportedAnalytics 13 | import com.jraska.dagger.codelab.app.ui.MainActivity 14 | import org.hamcrest.CoreMatchers.not 15 | import org.junit.Rule 16 | import org.junit.Test 17 | 18 | class AppTest { 19 | @get:Rule 20 | val activityRule = ActivityTestRule(MainActivity::class.java) 21 | 22 | @Test 23 | fun clickingDisablesButton() { 24 | onView(withId(R.id.main_bye_button)).check(matches(isDisplayed())) 25 | 26 | onView(withId(R.id.fab)).perform(click()) 27 | assertEventReported() 28 | onView(withText("bye_button")).perform(click()) 29 | 30 | pressBack() 31 | 32 | onView(withId(R.id.main_bye_button)).check(matches(not(isDisplayed()))) 33 | } 34 | 35 | private fun assertEventReported() { 36 | val event = activityRule.reportedAnalytics().findLast { it.key == "main_onFabClick" } 37 | if (event == null) { 38 | throw IllegalStateException("Fab event click not found") 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 14 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /app/src/main/java/com/jraska/dagger/codelab/app/DaggerApp.kt: -------------------------------------------------------------------------------- 1 | package com.jraska.dagger.codelab.app 2 | 3 | import android.app.Activity 4 | import android.app.Application 5 | import androidx.fragment.app.Fragment 6 | import com.jraska.dagger.codelab.app.di.AppComponent 7 | import com.jraska.dagger.codelab.app.di.DaggerAppComponent 8 | import com.jraska.dagger.codelab.core.di.HasAppComponent 9 | 10 | open class DaggerApp : Application(), HasAppComponent { 11 | val appComponent: AppComponent by lazy { 12 | createDaggerComponent() 13 | } 14 | 15 | open fun createDaggerComponent(): AppComponent { 16 | return DaggerAppComponent.builder() 17 | .setContext(this) 18 | .build() 19 | } 20 | 21 | override fun appComponent(): Any { 22 | return appComponent 23 | } 24 | 25 | override fun onCreate() { 26 | super.onCreate() 27 | appComponent.onAppCreateActions().forEach { it.onCreate() } 28 | } 29 | 30 | companion object { 31 | fun of(activity: Activity): DaggerApp { 32 | return activity.application as DaggerApp 33 | } 34 | 35 | fun of(fragment: Fragment): DaggerApp { 36 | return of(fragment.requireActivity()) 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /app/src/main/java/com/jraska/dagger/codelab/app/PackageName.kt: -------------------------------------------------------------------------------- 1 | package com.jraska.dagger.codelab.app 2 | 3 | import android.content.Context 4 | import javax.inject.Inject 5 | 6 | class PackageName @Inject constructor( 7 | val context: Context 8 | ) { 9 | fun thisAppPackage(): String { 10 | return context.applicationInfo.packageName 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/java/com/jraska/dagger/codelab/app/di/AppComponent.kt: -------------------------------------------------------------------------------- 1 | package com.jraska.dagger.codelab.app.di 2 | 3 | import android.content.Context 4 | import com.jraska.dagger.codelab.app.ui.MainActivity 5 | import com.jraska.dagger.codelab.app.ui.MainFragment 6 | import com.jraska.dagger.codelab.config.di.ConfigComponent 7 | import com.jraska.dagger.codelab.config.di.ConfigModule 8 | import com.jraska.dagger.codelab.core.analytics.di.AnalyticsModule 9 | import com.jraska.dagger.codelab.core.app.OnAppCreate 10 | import dagger.BindsInstance 11 | import dagger.Component 12 | import javax.inject.Singleton 13 | 14 | @Singleton 15 | @Component(modules = [AnalyticsModule::class, ConfigModule::class]) 16 | interface AppComponent : ConfigComponent { 17 | 18 | fun onAppCreateActions(): Set 19 | 20 | fun inject(mainFragment: MainFragment) 21 | 22 | fun inject(mainActivity: MainActivity) 23 | 24 | @Component.Builder 25 | interface Builder { 26 | @BindsInstance 27 | fun setContext(context: Context): Builder 28 | 29 | fun build(): AppComponent 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/java/com/jraska/dagger/codelab/app/ui/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.jraska.dagger.codelab.app.ui 2 | 3 | import android.os.Bundle 4 | import android.view.View 5 | import androidx.appcompat.app.AppCompatActivity 6 | import com.jraska.dagger.codelab.app.DaggerApp 7 | import com.jraska.dagger.codelab.app.PackageName 8 | import com.jraska.dagger.codelab.app.R 9 | import com.jraska.dagger.codelab.config.ui.ConfigActivity 10 | import com.jraska.dagger.codelab.core.analytics.AnalyticsEvent 11 | import com.jraska.dagger.codelab.core.analytics.EventAnalytics 12 | import javax.inject.Inject 13 | 14 | class MainActivity : AppCompatActivity() { 15 | 16 | @Inject 17 | lateinit var eventAnalytics: EventAnalytics 18 | 19 | @Inject 20 | lateinit var packageName: PackageName 21 | 22 | override fun onCreate(savedInstanceState: Bundle?) { 23 | DaggerApp.of(this).appComponent.inject(this) 24 | 25 | super.onCreate(savedInstanceState) 26 | setContentView(R.layout.activity_main) 27 | setSupportActionBar(findViewById(R.id.toolbar)) 28 | 29 | title = packageName.thisAppPackage() 30 | 31 | findViewById(R.id.fab).setOnClickListener { 32 | ConfigActivity.start(this) 33 | eventAnalytics.reportEvent(AnalyticsEvent.create("main_onFabClick")) 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /app/src/main/java/com/jraska/dagger/codelab/app/ui/MainFragment.kt: -------------------------------------------------------------------------------- 1 | package com.jraska.dagger.codelab.app.ui 2 | 3 | import android.os.Bundle 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import android.view.ViewGroup 7 | import androidx.fragment.app.Fragment 8 | import com.jraska.dagger.codelab.app.DaggerApp 9 | import com.jraska.dagger.codelab.app.R 10 | import com.jraska.dagger.codelab.config.di.CONFIG_BYE_BUTTON 11 | import com.jraska.dagger.codelab.core.config.RemoteConfig 12 | import javax.inject.Inject 13 | 14 | class MainFragment : Fragment() { 15 | 16 | @Inject 17 | lateinit var config: RemoteConfig 18 | 19 | override fun onCreate(savedInstanceState: Bundle?) { 20 | DaggerApp.of(this).appComponent.inject(this) 21 | 22 | super.onCreate(savedInstanceState) 23 | } 24 | 25 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { 26 | return inflater.inflate(R.layout.fragment_main, container, false) 27 | } 28 | 29 | override fun onResume() { 30 | super.onResume() 31 | 32 | val byeButton = requireView().findViewById(R.id.main_bye_button) 33 | if (config.getBoolean(CONFIG_BYE_BUTTON)) { 34 | byeButton.visibility = View.VISIBLE 35 | } else { 36 | byeButton.visibility = View.GONE 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 16 | 19 | 22 | 23 | 24 | 25 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 11 | 16 | 21 | 26 | 31 | 36 | 41 | 46 | 51 | 56 | 61 | 66 | 71 | 76 | 81 | 86 | 91 | 96 | 101 | 106 | 111 | 116 | 121 | 126 | 131 | 136 | 141 | 146 | 151 | 156 | 161 | 166 | 171 | 172 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 16 | 17 | 24 | 25 | 26 | 27 | 28 | 29 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /app/src/main/res/layout/content_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 |