├── .gitignore ├── LICENSE ├── README.md ├── annotations ├── .gitignore ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── kakai │ └── android │ └── autoviewmodelfactory │ └── annotations │ └── AutoViewModelFactory.java ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── kakai │ │ └── android │ │ └── autoviewmodelfactory │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── kakai │ │ │ └── android │ │ │ └── autoviewmodelfactory │ │ │ ├── App.java │ │ │ ├── data │ │ │ └── TestSingleton.java │ │ │ ├── di │ │ │ ├── components │ │ │ │ └── ApplicationComponent.java │ │ │ ├── modules │ │ │ │ ├── ApplicationModule.java │ │ │ │ └── activities │ │ │ │ │ ├── MainActivityModule.java │ │ │ │ │ └── binding │ │ │ │ │ └── ActivityBindingModule.java │ │ │ └── scopes │ │ │ │ ├── ActivityScope.java │ │ │ │ ├── ChildFragmentScope.java │ │ │ │ └── FragmentScope.java │ │ │ └── presentation │ │ │ ├── MainActivity.java │ │ │ └── MainViewModel.java │ └── res │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_foreground.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── kakai │ └── android │ └── autoviewmodelfactory │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── processor ├── .gitignore ├── build.gradle └── src │ └── main │ ├── java │ ├── android │ │ └── arch │ │ │ └── lifecycle │ │ │ ├── ViewModel.java │ │ │ └── ViewModelProvider.java │ └── com │ │ └── kakai │ │ └── android │ │ └── autoviewmodelfactory │ │ └── processor │ │ ├── AutoViewModelFactoryProcessor.java │ │ └── utils │ │ ├── AnnotationProcessingUtils.java │ │ └── StringUtils.java │ └── resources │ └── META-INF │ └── services │ └── javax.annotation.processing.Processor └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/java,android,osx,intellij,gradle 3 | 4 | ### Android ### 5 | # Built application files 6 | *.apk 7 | *.ap_ 8 | 9 | # Files for the ART/Dalvik VM 10 | *.dex 11 | 12 | # Java class files 13 | *.class 14 | 15 | # Generated files 16 | bin/ 17 | gen/ 18 | out/ 19 | 20 | # Gradle files 21 | .gradle/ 22 | build/ 23 | 24 | # Local configuration file (sdk path, etc) 25 | local.properties 26 | 27 | # Proguard folder generated by Eclipse 28 | proguard/ 29 | 30 | # Log Files 31 | *.log 32 | 33 | # Android Studio Navigation editor temp files 34 | .navigation/ 35 | 36 | # Android Studio captures folder 37 | captures/ 38 | 39 | # Intellij 40 | *.iml 41 | .idea/workspace.xml 42 | .idea/tasks.xml 43 | .idea/gradle.xml 44 | .idea/libraries 45 | 46 | # Keystore files 47 | #*.jks 48 | 49 | # External native build folder generated in Android Studio 2.2 and later 50 | .externalNativeBuild 51 | 52 | # Google Services (e.g. APIs or Firebase) 53 | #google-services.json 54 | 55 | # Freeline 56 | freeline.py 57 | freeline/ 58 | freeline_project_description.json 59 | 60 | ### Android Patch ### 61 | gen-external-apklibs 62 | 63 | ### Intellij ### 64 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 65 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 66 | 67 | # User-specific stuff: 68 | .idea/**/workspace.xml 69 | .idea/**/tasks.xml 70 | 71 | # Sensitive or high-churn files: 72 | .idea/**/dataSources/ 73 | .idea/**/dataSources.ids 74 | .idea/**/dataSources.xml 75 | .idea/**/dataSources.local.xml 76 | .idea/**/sqlDataSources.xml 77 | .idea/**/dynamic.xml 78 | .idea/**/uiDesigner.xml 79 | 80 | # Gradle: 81 | .idea/**/gradle.xml 82 | .idea/**/libraries 83 | 84 | # Mongo Explorer plugin: 85 | .idea/**/mongoSettings.xml 86 | 87 | ## File-based project format: 88 | *.iws 89 | 90 | ## Plugin-specific files: 91 | 92 | # IntelliJ 93 | /out/ 94 | 95 | # mpeltonen/sbt-idea plugin 96 | .idea_modules/ 97 | 98 | # JIRA plugin 99 | atlassian-ide-plugin.xml 100 | 101 | # Crashlytics plugin (for Android Studio and IntelliJ) 102 | com_crashlytics_export_strings.xml 103 | crashlytics.properties 104 | crashlytics-build.properties 105 | fabric.properties 106 | 107 | ### Intellij Patch ### 108 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 109 | 110 | # *.iml 111 | # modules.xml 112 | # .idea/misc.xml 113 | # *.ipr 114 | .idea 115 | 116 | ### Java ### 117 | # Compiled class file 118 | 119 | # Log file 120 | 121 | # BlueJ files 122 | *.ctxt 123 | 124 | # Mobile Tools for Java (J2ME) 125 | .mtj.tmp/ 126 | 127 | # Package Files # 128 | *.jar 129 | *.war 130 | *.ear 131 | *.zip 132 | *.tar.gz 133 | *.rar 134 | 135 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 136 | hs_err_pid* 137 | 138 | ### OSX ### 139 | *.DS_Store 140 | .AppleDouble 141 | .LSOverride 142 | 143 | # Icon must end with two \r 144 | Icon 145 | 146 | 147 | # Thumbnails 148 | ._* 149 | 150 | # Files that might appear in the root of a volume 151 | .DocumentRevisions-V100 152 | .fseventsd 153 | .Spotlight-V100 154 | .TemporaryItems 155 | .Trashes 156 | .VolumeIcon.icns 157 | .com.apple.timemachine.donotpresent 158 | 159 | # Directories potentially created on remote AFP share 160 | .AppleDB 161 | .AppleDesktop 162 | Network Trash Folder 163 | Temporary Items 164 | .apdisk 165 | 166 | ### Gradle ### 167 | .gradle 168 | /build/ 169 | 170 | # Ignore Gradle GUI config 171 | gradle-app.setting 172 | 173 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 174 | !gradle-wrapper.jar 175 | 176 | # Cache of project 177 | .gradletasknamecache 178 | 179 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 180 | # gradle/wrapper/gradle-wrapper.properties 181 | 182 | # End of https://www.gitignore.io/api/java,android,osx,intellij,gradle 183 | /app/build/ -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [DEPRECATED] AutoViewModelFactory 2 | ========================= 3 | [![](https://jitpack.io/v/kakai248/AutoViewModelFactory.svg)](https://jitpack.io/#kakai248/AutoViewModelFactory) 4 | 5 | This library generates the factory for the Architecture Components ViewModel. To be used with dagger2. 6 | 7 | Why is it deprecated? 8 | ------ 9 | After I built this library, I found a better way of doing this. We can have a single generic factory that receives the `ViewModel` created with dagger. 10 | ```kotlin 11 | class ViewModelFactory @Inject constructor(private val viewModel: Lazy) : ViewModelProvider.Factory { 12 | @Suppress("UNCHECKED_CAST") 13 | override fun create(modelClass: Class): T { 14 | return viewModel.get() as T 15 | } 16 | } 17 | ``` 18 | And then inject as usual: 19 | ```kotlin 20 | @Inject 21 | protected lateinit var viewModelFactory: ViewModelFactory 22 | 23 | lateinit var viewModel: ViewModel 24 | private set 25 | ``` 26 | ```kotlin 27 | viewModel = ViewModelProviders.of(this, viewModelFactory).get(viewModelClass()) 28 | ``` 29 | 30 | `Lazy` makes sure the ViewModel is only created when Arch components call `create`. This way we let dagger create everything and still use the `ViewModelStore`. 31 | 32 | Why do you need this? 33 | ------ 34 | If you are using Google's ViewModels and dagger2, you should have the problem of not being able to 35 | inject the ViewModel while using scoped parameters in its constructor that are provided by the Activity/Fragment/whatever. 36 | This happens because the ViewModel has a higher scope than the Activity or the Fragment. 37 | 38 | You have two options (that I know of): 39 | - You pass the parameters after the constructor. But you also have to manage if the ViewModel was already initialized. 40 | - Or you have a factory for each ViewModel. But you will need to create the factory manually. Unnecessary boilerplate. 41 | 42 | This library creates the factory for you, only using an annotation on the ViewModel. 43 | 44 | Installation 45 | ------ 46 | This library requires Java 8 to run the annotation processor. 47 | 48 | Check the latest version in the badge above. 49 | 50 | ```groovy 51 | repositories { 52 | maven { url "https://jitpack.io" } 53 | } 54 | ``` 55 | 56 | ```groovy 57 | compile "com.github.kakai248.AutoViewModelFactory:annotations:${LATEST_VERSION}" 58 | annotationProcessor "com.github.kakai248.AutoViewModelFactory:processor:${LATEST_VERSION}" 59 | ``` 60 | 61 | Usage 62 | ------- 63 | Annotate your ViewModel with `@AutoViewModelFactory`. Don't annotate the constructor with `@Inject` as you will no longer inject the ViewModel. 64 | You will inject the factory instead, and this one is created by dagger with the default scope (new instance each time). 65 | 66 | ```java 67 | @AutoViewModelFactory 68 | public class MainViewModel extends ViewModel { 69 | public MainViewModel() { 70 | } 71 | } 72 | ``` 73 | 74 | On your activity/fragment/whatever: 75 | ```java 76 | public class MainActivity extends DaggerAppCompatActivity { 77 | 78 | @Inject 79 | MainViewModelFactory viewModelFactory; 80 | 81 | private MainViewModel viewModel; 82 | 83 | @Override 84 | protected void onCreate(Bundle savedInstanceState) { 85 | AndroidInjection.inject(this); 86 | super.onCreate(savedInstanceState); 87 | setContentView(R.layout.activity_main); 88 | 89 | viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel.class); 90 | } 91 | } 92 | ``` 93 | 94 | Example 95 | ------ 96 | See the included sample app. 97 | 98 | Disclaimer 99 | ------ 100 | The annotation processor recreates the ViewModel package to be able to generate code while referencing it. If Google changes this, the processor may stop working. 101 | 102 | License 103 | ------- 104 | 105 | Copyright 2017 Ricardo Carrapiço 106 | 107 | Licensed under the Apache License, Version 2.0 (the "License"); 108 | you may not use this file except in compliance with the License. 109 | You may obtain a copy of the License at 110 | 111 | http://www.apache.org/licenses/LICENSE-2.0 112 | 113 | Unless required by applicable law or agreed to in writing, software 114 | distributed under the License is distributed on an "AS IS" BASIS, 115 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 116 | See the License for the specific language governing permissions and 117 | limitations under the License. 118 | -------------------------------------------------------------------------------- /annotations/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /annotations/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java-library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | 4 | dependencies { 5 | implementation fileTree(dir: 'libs', include: ['*.jar']) 6 | } 7 | 8 | sourceCompatibility = "1.7" 9 | targetCompatibility = "1.7" 10 | -------------------------------------------------------------------------------- /annotations/src/main/java/com/kakai/android/autoviewmodelfactory/annotations/AutoViewModelFactory.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.annotations; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.SOURCE) 9 | @Target(ElementType.TYPE) 10 | public @interface AutoViewModelFactory { 11 | } -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | buildToolsVersion "26.0.1" 6 | 7 | defaultConfig { 8 | applicationId "com.kakai.android.autoviewmodelfactory" 9 | minSdkVersion 19 10 | targetSdkVersion 26 11 | versionCode 1 12 | versionName "1.0" 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | } 15 | 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | implementation fileTree(dir: 'libs', include: ['*.jar']) 26 | 27 | // AutoViewModelFactory 28 | implementation project(':annotations') 29 | annotationProcessor project(':processor') 30 | 31 | // Android core 32 | implementation "com.android.support:design:$rootProject.supportLibraryVersion" 33 | implementation "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion" 34 | implementation 'com.android.support.constraint:constraint-layout:1.1.0-beta1' 35 | 36 | implementation "android.arch.lifecycle:runtime:$rootProject.architectureComponentsVersion" 37 | implementation "android.arch.lifecycle:extensions:$rootProject.architectureComponentsVersion" 38 | annotationProcessor "android.arch.lifecycle:compiler:$rootProject.architectureComponentsVersion" 39 | 40 | implementation 'com.google.code.findbugs:jsr305:3.0.2' 41 | 42 | // Dagger 43 | implementation "com.google.dagger:dagger-android-support:$rootProject.daggerVersion" 44 | annotationProcessor "com.google.dagger:dagger-compiler:$rootProject.daggerVersion" 45 | annotationProcessor "com.google.dagger:dagger-android-processor:$rootProject.daggerVersion" 46 | 47 | // LeakCanary 48 | debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.3' 49 | releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.3' 50 | 51 | // Tests 52 | testImplementation 'junit:junit:4.12' 53 | androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', { 54 | exclude group: 'com.android.support', module: 'support-annotations' 55 | }) 56 | } 57 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/kakai/android/autoviewmodelfactory/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.kakai.android.autoviewmodelfactory", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/App.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory; 2 | 3 | import com.kakai.android.autoviewmodelfactory.di.components.DaggerApplicationComponent; 4 | 5 | import dagger.android.AndroidInjector; 6 | import dagger.android.support.DaggerApplication; 7 | 8 | 9 | public class App extends DaggerApplication { 10 | 11 | @Override 12 | protected AndroidInjector applicationInjector() { 13 | return DaggerApplicationComponent.builder().create(this); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/data/TestSingleton.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.data; 2 | 3 | import javax.inject.Inject; 4 | import javax.inject.Singleton; 5 | 6 | @Singleton 7 | public class TestSingleton { 8 | 9 | @Inject 10 | public TestSingleton() { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/di/components/ApplicationComponent.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.di.components; 2 | 3 | import com.kakai.android.autoviewmodelfactory.App; 4 | import com.kakai.android.autoviewmodelfactory.di.modules.ApplicationModule; 5 | import com.kakai.android.autoviewmodelfactory.di.modules.activities.binding.ActivityBindingModule; 6 | 7 | import javax.inject.Singleton; 8 | 9 | import dagger.Component; 10 | import dagger.android.AndroidInjector; 11 | import dagger.android.support.AndroidSupportInjectionModule; 12 | 13 | @Component(modules = { 14 | ApplicationModule.class, 15 | ActivityBindingModule.class, 16 | AndroidSupportInjectionModule.class}) 17 | @Singleton 18 | interface ApplicationComponent extends AndroidInjector { 19 | 20 | @Component.Builder 21 | abstract class Builder extends AndroidInjector.Builder { 22 | } 23 | } -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/di/modules/ApplicationModule.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.di.modules; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | import com.kakai.android.autoviewmodelfactory.App; 7 | 8 | import javax.inject.Singleton; 9 | 10 | import dagger.Binds; 11 | import dagger.Module; 12 | import dagger.Provides; 13 | 14 | @Module 15 | public abstract class ApplicationModule { 16 | 17 | @Binds 18 | abstract Application application(App app); 19 | 20 | @Provides 21 | @Singleton 22 | static Context provideContext(Application application) { 23 | return application; 24 | } 25 | } -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/di/modules/activities/MainActivityModule.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.di.modules.activities; 2 | 3 | import android.support.v7.app.AppCompatActivity; 4 | 5 | import com.kakai.android.autoviewmodelfactory.di.scopes.ActivityScope; 6 | import com.kakai.android.autoviewmodelfactory.presentation.MainActivity; 7 | 8 | import javax.inject.Named; 9 | 10 | import dagger.Binds; 11 | import dagger.Module; 12 | import dagger.Provides; 13 | 14 | @Module 15 | public abstract class MainActivityModule { 16 | 17 | public static final String TEST_STRING = "testString"; 18 | public static final String ANOTHER_TEST_STRING = "anotherTestString"; 19 | 20 | @Binds 21 | abstract AppCompatActivity activity(MainActivity activity); 22 | 23 | @Provides 24 | @Named(TEST_STRING) 25 | @ActivityScope 26 | static String provideTestString(MainActivity activity) { 27 | return activity.getTestString(); 28 | } 29 | 30 | @Provides 31 | @Named(ANOTHER_TEST_STRING) 32 | @ActivityScope 33 | static String provideAnotherTestString(MainActivity activity) { 34 | return activity.getAnotherTestString(); 35 | } 36 | } -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/di/modules/activities/binding/ActivityBindingModule.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.di.modules.activities.binding; 2 | 3 | import com.kakai.android.autoviewmodelfactory.di.modules.activities.MainActivityModule; 4 | import com.kakai.android.autoviewmodelfactory.di.scopes.ActivityScope; 5 | import com.kakai.android.autoviewmodelfactory.presentation.MainActivity; 6 | 7 | import dagger.Module; 8 | import dagger.android.ContributesAndroidInjector; 9 | 10 | @Module 11 | public abstract class ActivityBindingModule { 12 | 13 | @ActivityScope 14 | @ContributesAndroidInjector(modules = MainActivityModule.class) 15 | abstract MainActivity mainActivity(); 16 | } -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/di/scopes/ActivityScope.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.di.scopes; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | import javax.inject.Scope; 7 | 8 | @Scope 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface ActivityScope { 11 | } -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/di/scopes/ChildFragmentScope.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.di.scopes; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | import javax.inject.Scope; 7 | 8 | @Scope 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface ChildFragmentScope { 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/di/scopes/FragmentScope.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.di.scopes; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.RetentionPolicy; 5 | 6 | import javax.inject.Scope; 7 | 8 | @Scope 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface FragmentScope { 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/presentation/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.presentation; 2 | 3 | import android.arch.lifecycle.Observer; 4 | import android.arch.lifecycle.ViewModelProviders; 5 | import android.os.Bundle; 6 | import android.support.annotation.Nullable; 7 | import android.widget.TextView; 8 | 9 | import com.kakai.android.autoviewmodelfactory.R; 10 | 11 | import javax.inject.Inject; 12 | 13 | import dagger.android.AndroidInjection; 14 | import dagger.android.support.DaggerAppCompatActivity; 15 | 16 | public class MainActivity extends DaggerAppCompatActivity { 17 | 18 | @Inject 19 | MainViewModelFactory viewModelFactory; 20 | 21 | private MainViewModel viewModel; 22 | 23 | @Override 24 | protected void onCreate(Bundle savedInstanceState) { 25 | AndroidInjection.inject(this); 26 | super.onCreate(savedInstanceState); 27 | setContentView(R.layout.activity_main); 28 | 29 | viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel.class); 30 | 31 | viewModel.getMessage().observe(this, new Observer() { 32 | @Override 33 | public void onChanged(@Nullable String message) { 34 | ((TextView) findViewById(R.id.message)).setText(message); 35 | } 36 | }); 37 | } 38 | 39 | public String getTestString() { 40 | return "test"; 41 | } 42 | 43 | public String getAnotherTestString() { 44 | return "another test"; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/com/kakai/android/autoviewmodelfactory/presentation/MainViewModel.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.presentation; 2 | 3 | import android.arch.lifecycle.LiveData; 4 | import android.arch.lifecycle.MutableLiveData; 5 | import android.arch.lifecycle.ViewModel; 6 | 7 | import com.kakai.android.autoviewmodelfactory.annotations.AutoViewModelFactory; 8 | import com.kakai.android.autoviewmodelfactory.data.TestSingleton; 9 | 10 | import javax.inject.Named; 11 | 12 | import static com.kakai.android.autoviewmodelfactory.di.modules.activities.MainActivityModule.ANOTHER_TEST_STRING; 13 | import static com.kakai.android.autoviewmodelfactory.di.modules.activities.MainActivityModule.TEST_STRING; 14 | 15 | @AutoViewModelFactory 16 | public class MainViewModel extends ViewModel { 17 | 18 | private TestSingleton testSingleton; 19 | private String testString; 20 | private String anotherTestString; 21 | 22 | private MutableLiveData message = new MutableLiveData<>(); 23 | 24 | public MainViewModel(TestSingleton testSingleton, 25 | @Named(TEST_STRING) String testString, 26 | @Named(ANOTHER_TEST_STRING) String anotherTestString) { 27 | this.testSingleton = testSingleton; 28 | this.testString = testString; 29 | this.anotherTestString = anotherTestString; 30 | 31 | message.setValue("Hello World!"); 32 | } 33 | 34 | public LiveData getMessage() { 35 | return message; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 13 | 18 | 23 | 28 | 33 | 38 | 43 | 48 | 53 | 58 | 63 | 68 | 73 | 78 | 83 | 88 | 93 | 98 | 103 | 108 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AutoViewModelFactory 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/kakai/android/autoviewmodelfactory/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | 5 | repositories { 6 | google() 7 | jcenter() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.0.0-beta6' 11 | 12 | 13 | // NOTE: Do not place your application dependencies here; they belong 14 | // in the individual module build.gradle files 15 | } 16 | } 17 | 18 | plugins { 19 | id "com.github.dcendents.android-maven" version "2.0" 20 | } 21 | 22 | allprojects { 23 | repositories { 24 | google() 25 | jcenter() 26 | maven { url 'https://dl.google.com/dl/android/maven2/' } 27 | } 28 | } 29 | 30 | ext { 31 | minSdkVersion = 19 32 | targetSdkVersion = 26 33 | compileSdkVersion = 26 34 | buildToolsVersion = '26.0.1' 35 | 36 | supportLibraryVersion = '26.1.0' 37 | architectureComponentsVersion = '1.0.0-alpha9-1' 38 | 39 | daggerVersion = '2.11' 40 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kakai248/AutoViewModelFactory/297eb88eb737667758f1a13627c9abe64433325b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Sep 20 15:08:13 WEST 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /processor/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /processor/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java-library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | 4 | dependencies { 5 | implementation fileTree(dir: 'libs', include: ['*.jar']) 6 | 7 | implementation project(':annotations') 8 | 9 | implementation 'com.squareup:javapoet:1.9.0' 10 | implementation 'javax.inject:javax.inject:1' 11 | } 12 | 13 | sourceCompatibility = "1.8" 14 | targetCompatibility = "1.8" 15 | -------------------------------------------------------------------------------- /processor/src/main/java/android/arch/lifecycle/ViewModel.java: -------------------------------------------------------------------------------- 1 | package android.arch.lifecycle; 2 | 3 | public class ViewModel { 4 | } 5 | -------------------------------------------------------------------------------- /processor/src/main/java/android/arch/lifecycle/ViewModelProvider.java: -------------------------------------------------------------------------------- 1 | package android.arch.lifecycle; 2 | 3 | public class ViewModelProvider { 4 | 5 | public interface Factory { 6 | 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /processor/src/main/java/com/kakai/android/autoviewmodelfactory/processor/AutoViewModelFactoryProcessor.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.processor; 2 | 3 | import android.arch.lifecycle.ViewModelProvider; 4 | 5 | import com.kakai.android.autoviewmodelfactory.annotations.AutoViewModelFactory; 6 | import com.kakai.android.autoviewmodelfactory.processor.utils.AnnotationProcessingUtils; 7 | import com.kakai.android.autoviewmodelfactory.processor.utils.StringUtils; 8 | import com.squareup.javapoet.AnnotationSpec; 9 | import com.squareup.javapoet.ClassName; 10 | import com.squareup.javapoet.JavaFile; 11 | import com.squareup.javapoet.MethodSpec; 12 | import com.squareup.javapoet.ParameterSpec; 13 | import com.squareup.javapoet.TypeName; 14 | import com.squareup.javapoet.TypeSpec; 15 | 16 | import java.io.IOException; 17 | import java.util.ArrayList; 18 | import java.util.HashSet; 19 | import java.util.LinkedHashMap; 20 | import java.util.List; 21 | import java.util.Map; 22 | import java.util.Set; 23 | 24 | import javax.annotation.processing.AbstractProcessor; 25 | import javax.annotation.processing.Filer; 26 | import javax.annotation.processing.FilerException; 27 | import javax.annotation.processing.Messager; 28 | import javax.annotation.processing.ProcessingEnvironment; 29 | import javax.annotation.processing.RoundEnvironment; 30 | import javax.annotation.processing.SupportedAnnotationTypes; 31 | import javax.annotation.processing.SupportedSourceVersion; 32 | import javax.inject.Inject; 33 | import javax.lang.model.SourceVersion; 34 | import javax.lang.model.element.AnnotationMirror; 35 | import javax.lang.model.element.Element; 36 | import javax.lang.model.element.ElementKind; 37 | import javax.lang.model.element.ExecutableElement; 38 | import javax.lang.model.element.Modifier; 39 | import javax.lang.model.element.TypeElement; 40 | import javax.lang.model.element.VariableElement; 41 | import javax.lang.model.util.Elements; 42 | import javax.tools.Diagnostic; 43 | 44 | @SupportedAnnotationTypes({ 45 | "com.kakai.android.autoviewmodelfactory.annotations.AutoViewModelFactory" 46 | }) 47 | @SupportedSourceVersion(SourceVersion.RELEASE_8) 48 | public class AutoViewModelFactoryProcessor extends AbstractProcessor { 49 | 50 | private static final String CLASS_SUFFIX = "Factory"; 51 | 52 | private static final String FACTORY_CREATE_METHOD_NAME = "create"; 53 | private static final String FACTORY_CREATE_METHOD_PARAMETER_NAME = "modelClass"; 54 | 55 | private Filer filer; 56 | private Messager messager; 57 | private Elements elements; 58 | private Set viewModels; 59 | 60 | @Override 61 | public synchronized void init(ProcessingEnvironment processingEnvironment) { 62 | super.init(processingEnvironment); 63 | filer = processingEnvironment.getFiler(); 64 | messager = processingEnvironment.getMessager(); 65 | elements = processingEnvironment.getElementUtils(); 66 | viewModels = new HashSet<>(); 67 | } 68 | 69 | @Override 70 | public boolean process(Set set, RoundEnvironment roundEnvironment) { 71 | 72 | try { 73 | if (!findAnnotatedViewModels(roundEnvironment)) { 74 | return true; 75 | } 76 | 77 | for (TypeElement viewModelElement : viewModels) { 78 | generateViewModelFactory(viewModelElement); 79 | } 80 | 81 | } catch (IOException e) { 82 | error("An error has occurred."); 83 | e.printStackTrace(); 84 | } 85 | 86 | return true; 87 | } 88 | 89 | private boolean findAnnotatedViewModels(RoundEnvironment roundEnvironment) { 90 | for (Element element : roundEnvironment.getElementsAnnotatedWith(AutoViewModelFactory.class)) { 91 | 92 | if (element.getKind() != ElementKind.CLASS) { 93 | error(element, "Only classes can be annotated with @%s.", 94 | AutoViewModelFactory.class.getSimpleName()); 95 | return false; 96 | } 97 | 98 | TypeElement typeElement = (TypeElement) element; 99 | viewModels.add(typeElement); 100 | } 101 | 102 | return true; 103 | } 104 | 105 | private void generateViewModelFactory(TypeElement viewModelElement) throws IOException { 106 | String packageName = elements.getPackageOf(viewModelElement).getQualifiedName().toString(); 107 | String viewModelName = viewModelElement.getSimpleName().toString(); 108 | 109 | // Build class 110 | TypeSpec.Builder factoryClass = TypeSpec 111 | .classBuilder(viewModelName + CLASS_SUFFIX) 112 | .addModifiers(Modifier.PUBLIC, Modifier.FINAL) 113 | .addSuperinterface(TypeName.get(ViewModelProvider.Factory.class)); 114 | 115 | // ViewModel dependencies 116 | LinkedHashMap viewModelDependencies = new LinkedHashMap<>(); 117 | 118 | List constructorParams = new ArrayList<>(); 119 | 120 | // Class methods 121 | for (Element classElement : elements.getAllMembers(viewModelElement)) { 122 | if (AnnotationProcessingUtils.isConstructor(classElement)) { 123 | ExecutableElement methodElement = (ExecutableElement) classElement; 124 | 125 | // Constructor parameters 126 | for (VariableElement variableElement : methodElement.getParameters()) { 127 | TypeName parameterTypeName = TypeName.get(variableElement.asType()); 128 | String parameterName = variableElement.getSimpleName().toString(); 129 | 130 | // Add the annotations that each parameter has (mainly to copy @Named) 131 | List parameterAnnotations = new ArrayList<>(); 132 | for (AnnotationMirror annotation : elements.getAllAnnotationMirrors(variableElement)) { 133 | parameterAnnotations.add(AnnotationSpec.get(annotation)); 134 | } 135 | 136 | viewModelDependencies.put(parameterName, parameterTypeName); 137 | constructorParams.add( 138 | ParameterSpec.builder(parameterTypeName, parameterName) 139 | .addAnnotations(parameterAnnotations) 140 | .build() 141 | ); 142 | } 143 | } 144 | } 145 | 146 | // Build constructor 147 | MethodSpec.Builder constructorMethod = MethodSpec 148 | .constructorBuilder() 149 | .addModifiers(Modifier.PUBLIC) 150 | .addAnnotation(Inject.class) 151 | .addParameters(constructorParams); 152 | 153 | // Build create method 154 | MethodSpec.Builder createMethod = MethodSpec 155 | .methodBuilder(FACTORY_CREATE_METHOD_NAME) 156 | .addModifiers(Modifier.PUBLIC) 157 | .addAnnotation(Override.class) 158 | .addParameter(ClassName.get(Class.class), FACTORY_CREATE_METHOD_PARAMETER_NAME) 159 | .returns(TypeName.get(viewModelElement.asType())); 160 | 161 | // Add the ViewModel dependencies to the generated factory 162 | for (Map.Entry entry : viewModelDependencies.entrySet()) { 163 | // Class field 164 | factoryClass.addField(entry.getValue(), entry.getKey(), Modifier.PRIVATE); 165 | 166 | // Constructor param 167 | constructorMethod.addStatement("this.$N = $L", entry.getKey(), entry.getKey()); 168 | } 169 | 170 | // Add the ViewModel instantiation statement to the create method 171 | createMethod.addStatement( 172 | String.format("return ($T) new $T(%s)", StringUtils.join(viewModelDependencies.keySet(), ", ")), 173 | viewModelElement, 174 | viewModelElement 175 | ); 176 | 177 | factoryClass.addMethod(constructorMethod.build()); 178 | factoryClass.addMethod(createMethod.build()); 179 | 180 | try { 181 | // Write the factory to a file 182 | JavaFile.builder(packageName, factoryClass.build()).build().writeTo(filer); 183 | } catch (FilerException e) { 184 | System.err.println(String.format("%s: %s", e.getClass().getSimpleName(), e.getMessage())); 185 | } 186 | } 187 | 188 | private void error(String msg, Object... args) { 189 | messager.printMessage(Diagnostic.Kind.ERROR, String.format(msg, args)); 190 | } 191 | 192 | private void error(Element e, String msg, Object... args) { 193 | messager.printMessage(Diagnostic.Kind.ERROR, String.format(msg, args), e); 194 | } 195 | } -------------------------------------------------------------------------------- /processor/src/main/java/com/kakai/android/autoviewmodelfactory/processor/utils/AnnotationProcessingUtils.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.processor.utils; 2 | 3 | import javax.lang.model.element.Element; 4 | import javax.lang.model.element.ExecutableElement; 5 | 6 | public class AnnotationProcessingUtils { 7 | 8 | public static boolean isConstructor(Element element) { 9 | return element instanceof ExecutableElement && element.getSimpleName().contentEquals(""); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /processor/src/main/java/com/kakai/android/autoviewmodelfactory/processor/utils/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.kakai.android.autoviewmodelfactory.processor.utils; 2 | 3 | import java.util.Collection; 4 | import java.util.stream.Collectors; 5 | 6 | public class StringUtils { 7 | 8 | public static String join(Collection collection, String delimiter) { 9 | return collection.stream().collect(Collectors.joining(delimiter)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor: -------------------------------------------------------------------------------- 1 | com.kakai.android.autoviewmodelfactory.processor.AutoViewModelFactoryProcessor -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':annotations', ':processor' 2 | --------------------------------------------------------------------------------