├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.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
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ └── activity_sample.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── radutopor
│ │ │ │ └── viewmodelfactory
│ │ │ │ ├── DI.kt
│ │ │ │ ├── SampleViewModel.kt
│ │ │ │ └── SampleActivity.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── radutopor
│ │ │ └── viewmodelfactory
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── radutopor
│ │ └── viewmodelfactory
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── annotations
├── .gitignore
├── src
│ └── main
│ │ └── java
│ │ └── com
│ │ └── radutopor
│ │ └── viewmodelfactory
│ │ └── annotations
│ │ ├── Provided.java
│ │ └── ViewModelFactory.java
└── build.gradle
├── processor
├── .gitignore
├── src
│ └── main
│ │ └── java
│ │ └── com
│ │ └── radutopor
│ │ └── viewmodelfactory
│ │ └── processor
│ │ ├── VmConstrParam.java
│ │ └── ViewModelFactoryProcessor.java
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── codeStyles
│ ├── codeStyleConfig.xml
│ └── Project.xml
├── vcs.xml
├── runConfigurations.xml
├── modules.xml
└── misc.xml
├── gradle.properties
├── .gitignore
├── gradlew.bat
├── README.md
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/annotations/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/processor/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':annotations', ':processor'
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ViewModelFactory
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radutopor/ViewModelFactory/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/annotations/src/main/java/com/radutopor/viewmodelfactory/annotations/Provided.java:
--------------------------------------------------------------------------------
1 | package com.radutopor.viewmodelfactory.annotations;
2 |
3 | import java.lang.annotation.Target;
4 |
5 | import static java.lang.annotation.ElementType.PARAMETER;
6 |
7 | /**
8 | * An annotation to be applied to parameters that should be provided by dependency injection in a generated factory.
9 | */
10 | @Target(PARAMETER)
11 | public @interface Provided {
12 | }
13 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/radutopor/viewmodelfactory/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.radutopor.viewmodelfactory
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/annotations/src/main/java/com/radutopor/viewmodelfactory/annotations/ViewModelFactory.java:
--------------------------------------------------------------------------------
1 | package com.radutopor.viewmodelfactory.annotations;
2 |
3 | import java.lang.annotation.Target;
4 |
5 | import static java.lang.annotation.ElementType.CONSTRUCTOR;
6 | import static java.lang.annotation.ElementType.TYPE;
7 |
8 | /**
9 | * An annotation to be applied to ViewModels for which a ViewModelProvider.Factory should be automatically generated.
10 | */
11 | @Target({TYPE, CONSTRUCTOR})
12 | public @interface ViewModelFactory {
13 | }
14 |
--------------------------------------------------------------------------------
/app/src/main/java/com/radutopor/viewmodelfactory/DI.kt:
--------------------------------------------------------------------------------
1 | package com.radutopor.viewmodelfactory
2 |
3 | import dagger.Component
4 | import dagger.Module
5 | import dagger.Provides
6 | import javax.inject.Singleton
7 |
8 | @Module
9 | class AppModule {
10 | @Singleton
11 | @Provides
12 | fun providesAppName() = "SampleApp"
13 | }
14 |
15 | @Singleton
16 | @Component(modules = [AppModule::class])
17 | interface AppComponent {
18 | fun inject(sampleActivity: SampleActivity)
19 | }
20 |
21 | val appComponent = DaggerAppComponent.create()
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_sample.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/radutopor/viewmodelfactory/SampleViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.radutopor.viewmodelfactory
2 |
3 | import androidx.lifecycle.LiveData
4 | import androidx.lifecycle.MutableLiveData
5 | import androidx.lifecycle.ViewModel
6 | import com.radutopor.viewmodelfactory.annotations.Provided
7 | import com.radutopor.viewmodelfactory.annotations.ViewModelFactory
8 |
9 | @ViewModelFactory
10 | class SampleViewModel(@Provided private val appName: String, private val userName: String) : ViewModel() {
11 | private val greeting = MutableLiveData()
12 |
13 | init {
14 | greeting.value = "Hi $userName, this is $appName"
15 | }
16 |
17 | fun getGreeting() = greeting as LiveData
18 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/radutopor/viewmodelfactory/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.radutopor.viewmodelfactory
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getTargetContext()
22 | assertEquals("com.radutopor.viewmodelfactory", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/radutopor/viewmodelfactory/processor/VmConstrParam.java:
--------------------------------------------------------------------------------
1 | package com.radutopor.viewmodelfactory.processor;
2 |
3 | public class VmConstrParam {
4 | private final String type;
5 | private final String name;
6 | private final String typeAndName;
7 | private final boolean isProvided;
8 |
9 | public VmConstrParam(String type, String name, boolean isProvided) {
10 | this.type = type;
11 | this.name = name;
12 | typeAndName = type + " " + name;
13 | this.isProvided = isProvided;
14 | }
15 |
16 | public String getType() {
17 | return type;
18 | }
19 |
20 | public String getName() {
21 | return name;
22 | }
23 |
24 | public String getTypeAndName() {
25 | return typeAndName;
26 | }
27 |
28 | public boolean isProvided() {
29 | return isProvided;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # Kotlin code style for this project: "official" or "obsolete":
15 | kotlin.code.style=official
16 | android.enableJetifier=true
17 | android.useAndroidX=true
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/radutopor/viewmodelfactory/SampleActivity.kt:
--------------------------------------------------------------------------------
1 | package com.radutopor.viewmodelfactory
2 |
3 | import android.os.Bundle
4 | import androidx.appcompat.app.AppCompatActivity
5 | import androidx.lifecycle.Observer
6 | import androidx.lifecycle.ViewModelProviders
7 | import kotlinx.android.synthetic.main.activity_sample.*
8 | import javax.inject.Inject
9 |
10 | class SampleActivity : AppCompatActivity() {
11 | @Inject
12 | lateinit var sampleViewModelFactory2: SampleViewModelFactory2
13 |
14 | override fun onCreate(savedInstanceState: Bundle?) {
15 | super.onCreate(savedInstanceState)
16 | setContentView(R.layout.activity_sample)
17 | appComponent.inject(this)
18 |
19 | val userName = intent.getStringExtra("USER_NAME") ?: "Billy"
20 | val viewModel = ViewModelProviders.of(this, sampleViewModelFactory2.create(userName))
21 | .get(SampleViewModel::class.java)
22 |
23 | viewModel.getGreeting().observe(this, Observer { greeting ->
24 | greetingTextView.text = greeting
25 | })
26 | }
27 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # IntelliJ
36 | *.iml
37 | .idea/workspace.xml
38 | .idea/tasks.xml
39 | .idea/gradle.xml
40 | .idea/assetWizardSettings.xml
41 | .idea/dictionaries
42 | .idea/libraries
43 | .idea/caches
44 |
45 | # Keystore files
46 | # Uncomment the following line if you do not want to check your keystore files in.
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 | # fastlane
61 | fastlane/report.xml
62 | fastlane/Preview.html
63 | fastlane/screenshots
64 | fastlane/test_output
65 | fastlane/readme.md
66 |
--------------------------------------------------------------------------------
/annotations/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java-library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | apply plugin: 'com.jfrog.bintray'
4 |
5 | dependencies {
6 | implementation fileTree(dir: 'libs', include: ['*.jar'])
7 | }
8 |
9 | sourceCompatibility = "7"
10 | targetCompatibility = "7"
11 |
12 | ext {
13 | bintrayRepo = 'ViewModelFactory'
14 | bintrayName = 'annotations'
15 |
16 | publishedGroupId = 'com.radutopor.viewmodelfactory'
17 | libraryName = 'ViewModelFactory'
18 | artifact = 'annotations'
19 |
20 | libraryDescription = 'Automatically generate factories for (Android Architecture Component\'s) ViewModels to enable assisted dependency injection'
21 |
22 | siteUrl = 'https://github.com/radutopor/ViewModelFactory'
23 | gitUrl = 'https://github.com/radutopor/ViewModelFactory.git'
24 |
25 | libraryVersion = '1.0.0'
26 |
27 | developerId = 'radutopor'
28 | developerName = 'Radu Topor'
29 | developerEmail = 'radu.ilie.topor@gmail.com'
30 |
31 | licenseName = 'The Apache Software License, Version 2.0'
32 | licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
33 | allLicenses = ["Apache-2.0"]
34 | }
35 |
36 | apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle'
37 | apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle'
--------------------------------------------------------------------------------
/processor/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java-library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | apply plugin: 'com.jfrog.bintray'
4 |
5 | dependencies {
6 | implementation fileTree(dir: 'libs', include: ['*.jar'])
7 | implementation project(path: ':annotations')
8 | implementation "com.google.auto.service:auto-service:1.0-rc4"
9 | }
10 |
11 | sourceCompatibility = "7"
12 | targetCompatibility = "7"
13 |
14 | ext {
15 | bintrayRepo = 'ViewModelFactory'
16 | bintrayName = 'processor'
17 |
18 | publishedGroupId = 'com.radutopor.viewmodelfactory'
19 | libraryName = 'ViewModelFactory'
20 | artifact = 'processor'
21 |
22 | libraryDescription = 'Automatically generate factories for (Android Architecture Component\'s) ViewModels to enable assisted dependency injection'
23 |
24 | siteUrl = 'https://github.com/radutopor/ViewModelFactory'
25 | gitUrl = 'https://github.com/radutopor/ViewModelFactory.git'
26 |
27 | libraryVersion = '1.0.0'
28 |
29 | developerId = 'radutopor'
30 | developerName = 'Radu Topor'
31 | developerEmail = 'radu.ilie.topor@gmail.com'
32 |
33 | licenseName = 'The Apache Software License, Version 2.0'
34 | licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
35 | allLicenses = ["Apache-2.0"]
36 | }
37 |
38 | apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle'
39 | apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle'
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | apply plugin: 'kotlin-android'
4 |
5 | apply plugin: 'kotlin-android-extensions'
6 |
7 | apply plugin: 'kotlin-kapt'
8 |
9 | kapt {
10 | correctErrorTypes = true
11 | }
12 |
13 | android {
14 | compileSdkVersion 28
15 | defaultConfig {
16 | applicationId "com.radutopor.viewmodelfactory"
17 | minSdkVersion 15
18 | targetSdkVersion 28
19 | versionCode 1
20 | versionName "1.0"
21 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
22 | }
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 | }
30 |
31 | dependencies {
32 | implementation fileTree(dir: 'libs', include: ['*.jar'])
33 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
34 | implementation "androidx.appcompat:appcompat:1.0.1"
35 |
36 | def lifecycle_version = "2.0.0"
37 | implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
38 | kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
39 | testImplementation "androidx.arch.core:core-testing:$lifecycle_version"
40 |
41 | def dagger_version = "2.19"
42 | implementation "com.google.dagger:dagger:$dagger_version"
43 | implementation "com.google.dagger:dagger-android-support:$dagger_version"
44 | kapt "com.google.dagger:dagger-compiler:$dagger_version"
45 |
46 | implementation project(path: ':annotations')
47 | kapt project(path: ':processor')
48 |
49 | testImplementation 'junit:junit:4.12'
50 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
51 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/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 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
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 Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ViewModelFactory
2 | #### Automatically generate factories for (Android Architecture Component's) ViewModels to enable easy assisted dependency injection
3 |
4 | This is an annotation processing library that generates a `ViewModelProvider.Factory`s for each `ViewModel` that allow easy and clean assisted dependency injection by any JSR-330-compatible library, like Dagger.
5 | This means that any `ViewModel` can be provided with both **common dependencies** _and_ **variable parameters** in the same constructor.
6 |
7 | ```
8 | @ViewModelFactory
9 | class SampleViewModel(@Provided private val repository: Repository, private val userId: Int) : ViewModel() {
10 | private val greeting = MutableLiveData()
11 |
12 | init {
13 | val user = repository.getUser(userId)
14 | greeting.value = "Hello, $user.name"
15 | }
16 |
17 | fun getGreeting() = greeting as LiveData
18 | }
19 | ```
20 | ```
21 | class SampleActivity : AppCompatActivity() {
22 | @Inject
23 | lateinit var sampleViewModelFactory2: SampleViewModelFactory2
24 |
25 | override fun onCreate(savedInstanceState: Bundle?) {
26 | super.onCreate(savedInstanceState)
27 | setContentView(R.layout.activity_sample)
28 | appComponent.inject(this)
29 |
30 | val userId = intent.getIntExtra("USER_ID", -1)
31 | val viewModel = ViewModelProviders.of(this, sampleViewModelFactory2.create(userId))
32 | .get(SampleViewModel::class.java)
33 |
34 | viewModel.getGreeting().observe(this, Observer { greeting ->
35 | greetingTextView.text = greeting
36 | })
37 | }
38 | }
39 | ```
40 |
41 | - `@ViewModelFactory` - Annotate either the `ViewModel` class or the specific constructor to be used by the factory
42 | - `@Provided` - Annotate all constructor arguments that can be provided by the graph of the dependency injection library
43 | - The rest of the variable constructor arguments will be taken by the factory in the `create()` method
44 | - You can inject the generated factory in your `Activity` or `Fragment` and use it to effortlessly construct dependency-satisfied and parametrised `ViewModel`s
45 |
46 | ## Installation
47 | In your `app.gradle` file:
48 | ```
49 | apply plugin: 'kotlin-kapt'
50 | // The following is currently needed with kapt when a library uses other generated code in its own annotation processing step
51 | // (i.e. Dagger using ViewModelFactory generated classes to complete its dependency graph)
52 | kapt {
53 | correctErrorTypes = true
54 | }
55 |
56 | implementation "com.radutopor.viewmodelfactory:annotations:1.0.0"
57 | kapt "com.radutopor.viewmodelfactory:processor:1.0.0" // use `annotationProcessor` for Java
58 | ```
59 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/processor/src/main/java/com/radutopor/viewmodelfactory/processor/ViewModelFactoryProcessor.java:
--------------------------------------------------------------------------------
1 | package com.radutopor.viewmodelfactory.processor;
2 |
3 | import com.google.auto.service.AutoService;
4 | import com.radutopor.viewmodelfactory.annotations.Provided;
5 | import com.radutopor.viewmodelfactory.annotations.ViewModelFactory;
6 |
7 | import javax.annotation.processing.AbstractProcessor;
8 | import javax.annotation.processing.Processor;
9 | import javax.annotation.processing.RoundEnvironment;
10 | import javax.annotation.processing.SupportedSourceVersion;
11 | import javax.lang.model.SourceVersion;
12 | import javax.lang.model.element.*;
13 | import javax.lang.model.util.ElementFilter;
14 | import javax.tools.Diagnostic;
15 | import javax.tools.JavaFileObject;
16 | import java.io.IOException;
17 | import java.io.Writer;
18 | import java.util.ArrayList;
19 | import java.util.HashSet;
20 | import java.util.List;
21 | import java.util.Set;
22 |
23 | @SupportedSourceVersion(SourceVersion.RELEASE_8)
24 | @AutoService(Processor.class)
25 | public class ViewModelFactoryProcessor extends AbstractProcessor {
26 | @Override
27 | public Set getSupportedAnnotationTypes() {
28 | return new HashSet() {{
29 | add(ViewModelFactory.class.getCanonicalName());
30 | }};
31 | }
32 |
33 | @Override
34 | public boolean process(Set extends TypeElement> set, RoundEnvironment roundEnvironment) {
35 | for (Element element : roundEnvironment.getElementsAnnotatedWith(ViewModelFactory.class)) {
36 | if (element.getKind() == ElementKind.CONSTRUCTOR) {
37 | createViewModelFactory2((ExecutableElement) element);
38 | } else if (element.getKind() == ElementKind.CLASS) {
39 | List constructors = ElementFilter.constructorsIn(element.getEnclosedElements());
40 | if (constructors.size() > 1) {
41 | processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Multiple constructors - Annotate one with `ViewModelFactory` instead of class");
42 | return true;
43 | } else {
44 | createViewModelFactory2(constructors.get(0));
45 | }
46 | } else {
47 | processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "`ViewModelFactory` annotation can only be applied to classes or constructors");
48 | return true;
49 | }
50 | }
51 | return false;
52 | }
53 |
54 | private void createViewModelFactory2(ExecutableElement vmConstructor) {
55 | TypeElement viewModel = (TypeElement) vmConstructor.getEnclosingElement();
56 | String packageName = processingEnv.getElementUtils().getPackageOf(viewModel).getQualifiedName().toString();
57 | String vmName = viewModel.getSimpleName().toString();
58 |
59 | StringBuilder factoryMembers = new StringBuilder();
60 | StringBuilder factoryConstrParams = new StringBuilder();
61 | StringBuilder factoryConstrStatements = new StringBuilder();
62 | StringBuilder vmCreateArgs = new StringBuilder();
63 | StringBuilder factory2Members = new StringBuilder();
64 | StringBuilder factory2ConstrParams = new StringBuilder();
65 | StringBuilder factory2ConstrStatements = new StringBuilder();
66 | StringBuilder factoryCreateParams = new StringBuilder();
67 | StringBuilder factoryCreateArgs = new StringBuilder();
68 |
69 | for (VmConstrParam vmConstrParam : getVmConstrParams(vmConstructor)) {
70 | append(factoryMembers, "private final %s;\n", vmConstrParam.getTypeAndName());
71 | append(factoryConstrParams, ", %s", vmConstrParam.getTypeAndName());
72 | append(factoryConstrStatements, "this.%1$s = %1$s;\n", vmConstrParam.getName());
73 | append(vmCreateArgs, ", %s", vmConstrParam.getName());
74 | if (vmConstrParam.isProvided()) {
75 | append(factory2Members, "private final Provider<%s> %sProvider;\n", vmConstrParam.getType(), vmConstrParam.getName());
76 | append(factory2ConstrParams, ", Provider<%s> %sProvider", vmConstrParam.getType(), vmConstrParam.getName());
77 | append(factory2ConstrStatements, "this.%1$sProvider = %1$sProvider;\n", vmConstrParam.getName());
78 | append(factoryCreateArgs, ", %sProvider.get()", vmConstrParam.getName());
79 | } else {
80 | append(factoryCreateParams, ", %s", vmConstrParam.getTypeAndName());
81 | append(factoryCreateArgs, ", %s", vmConstrParam.getName());
82 | }
83 | }
84 |
85 | trimFirstSeparator(factoryConstrParams);
86 | trimFirstSeparator(vmCreateArgs);
87 | trimFirstSeparator(factory2ConstrParams);
88 | trimFirstSeparator(factoryCreateParams);
89 | trimFirstSeparator(factoryCreateArgs);
90 |
91 | String factory2File = String.format("" +
92 | "package %1$s;\n" +
93 | "\n" +
94 | "import javax.inject.Inject;\n" +
95 | "import javax.inject.Provider;\n" +
96 | "\n" +
97 | "import androidx.annotation.NonNull;\n" +
98 | "import androidx.lifecycle.ViewModel;\n" +
99 | "import androidx.lifecycle.ViewModelProvider;\n" +
100 | "\n" +
101 | "public class %2$sFactory2 {\n" +
102 | " private static class %2$sFactory implements ViewModelProvider.Factory {\n" +
103 | " %3$s\n" +
104 | "\n" +
105 | " public %2$sFactory(%4$s) {\n" +
106 | " %5$s\n" +
107 | " }\n" +
108 | "\n" +
109 | " @NonNull\n" +
110 | " @Override\n" +
111 | " public T create(@NonNull Class modelClass) {\n" +
112 | " return (T) new %2$s(%6$s);\n" +
113 | " }\n" +
114 | " }\n" +
115 | "\n" +
116 | " %7$s\n" +
117 | "\n" +
118 | " @Inject\n" +
119 | " public %2$sFactory2(%8$s) {\n" +
120 | " %9$s\n" +
121 | " }\n" +
122 | "\n" +
123 | " public ViewModelProvider.Factory create(%10$s) {\n" +
124 | " return new %2$sFactory(%11$s);\n" +
125 | " }\n" +
126 | "}\n",
127 | packageName,
128 | vmName,
129 | factoryMembers,
130 | factoryConstrParams,
131 | factoryConstrStatements,
132 | vmCreateArgs,
133 | factory2Members,
134 | factory2ConstrParams,
135 | factory2ConstrStatements,
136 | factoryCreateParams,
137 | factoryCreateArgs);
138 |
139 | try {
140 | JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(viewModel.getQualifiedName() + "Factory2");
141 | Writer writer = builderFile.openWriter();
142 | writer.write(factory2File);
143 | writer.flush();
144 | writer.close();
145 | } catch (IOException e) {
146 | processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
147 | }
148 | }
149 |
150 | private List getVmConstrParams(ExecutableElement vmConstructor) {
151 | List vmConstrParams = new ArrayList<>();
152 | for (VariableElement param : vmConstructor.getParameters()) {
153 | vmConstrParams.add(new VmConstrParam(
154 | param.asType().toString(),
155 | param.getSimpleName().toString(),
156 | param.getAnnotation(Provided.class) != null));
157 | }
158 | return vmConstrParams;
159 | }
160 |
161 | private void append(StringBuilder stringBuilder, String format, String... args) {
162 | stringBuilder.append(String.format(format, args));
163 | }
164 |
165 | private void trimFirstSeparator(StringBuilder stringBuilder) {
166 | if (stringBuilder.length() > 2) {
167 | stringBuilder.delete(0, 2);
168 | }
169 | }
170 | }
171 |
--------------------------------------------------------------------------------