├── sample
├── .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
│ │ │ ├── main_activity.xml
│ │ │ └── sample_activity.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── wada811
│ │ └── viewmodelsavedstatektx
│ │ └── sample
│ │ ├── MainActivity.kt
│ │ ├── SampleViewModel.kt
│ │ └── SampleActivity.kt
├── proguard-rules.pro
└── build.gradle
├── ViewModel-SavedState-ktx
├── .gitignore
├── src
│ └── main
│ │ └── java
│ │ └── com
│ │ └── wada811
│ │ └── viewmodelsavedstatektx
│ │ ├── SavedStateAdapter.kt
│ │ ├── property
│ │ ├── SavedStateLiveDataProperty.kt
│ │ ├── SavedStateProperty.kt
│ │ ├── SavedStateSerializableProperty.kt
│ │ └── SavedStateLiveDataSerializableProperty.kt
│ │ ├── SavedStateHandles.kt
│ │ └── extension
│ │ ├── Intent.kt
│ │ └── Bundle.kt
├── build.gradle
└── proguard-rules.pro
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .envrc.template
├── settings.gradle
├── renovate.json
├── publish-root.gradle
├── .github
└── workflows
│ └── maven-publish.yml
├── gradle.properties
├── publish-module.gradle
├── gradlew.bat
├── README.md
├── .gitignore
├── gradlew
└── LICENSE
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SavedStateViewModel
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wada811/ViewModel-SavedState-ktx/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.envrc.template:
--------------------------------------------------------------------------------
1 | export OSSRH_USERNAME=
2 | export OSSRH_PASSWORD=
3 | export SONATYPE_STAGING_PROFILE_ID=
4 | export SIGNING_KEY_ID=
5 | export SIGNING_PASSWORD=
6 | export SIGNING_KEY=
7 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/src/main/java/com/wada811/viewmodelsavedstatektx/SavedStateAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.wada811.viewmodelsavedstatektx
2 |
3 | interface SavedStateAdapter {
4 | fun toSavedState(value: TValue): TState
5 | fun fromSavedState(state: TState): TValue
6 | }
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = 'Android-ViewModel-SavedState-ktx'
16 | include ':ViewModel-SavedState-ktx', ':sample'
17 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": [
3 | "config:base"
4 | ],
5 | "dependencyDashboard": true,
6 | "packageRules": [
7 | {
8 | "groupName": "Android Gradle Plugin",
9 | "matchPackagePatterns": [
10 | "com\\.android\\.application",
11 | "com\\.android\\.library"
12 | ]
13 | },
14 | {
15 | "groupName": "Kotlin",
16 | "matchPackagePatterns": [
17 | "^org\\.jetbrains\\.kotlin"
18 | ]
19 | }
20 | ]
21 | }
22 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/main_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
15 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'com.diffplug.spotless'
4 | id 'org.jetbrains.kotlin.android'
5 | }
6 |
7 | apply from: "${rootDir}/publish-module.gradle"
8 |
9 | android {
10 | namespace "com.wada811.viewmodelsavedstatektx"
11 | compileSdkVersion 33
12 | defaultConfig {
13 | minSdkVersion 21
14 | }
15 | }
16 |
17 | dependencies {
18 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.9.10"
19 | implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.6.1'
20 | implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.6.1'
21 | }
22 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/src/main/java/com/wada811/viewmodelsavedstatektx/property/SavedStateLiveDataProperty.kt:
--------------------------------------------------------------------------------
1 | package com.wada811.viewmodelsavedstatektx.property
2 |
3 | import androidx.lifecycle.MutableLiveData
4 | import androidx.lifecycle.SavedStateHandle
5 | import androidx.lifecycle.ViewModel
6 | import kotlin.properties.ReadOnlyProperty
7 | import kotlin.reflect.KProperty
8 |
9 | internal class SavedStateLiveDataProperty(
10 | private val savedStateHandle: SavedStateHandle
11 | ) : ReadOnlyProperty> {
12 | override fun getValue(thisRef: ViewModel, property: KProperty<*>): MutableLiveData {
13 | return savedStateHandle.getLiveData(property.name)
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/publish-root.gradle:
--------------------------------------------------------------------------------
1 | ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME')
2 | ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD')
3 | ext["sonatypeStagingProfileId"] = System.getenv('SONATYPE_STAGING_PROFILE_ID')
4 | ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID')
5 | ext["signing.password"] = System.getenv('SIGNING_PASSWORD')
6 | ext["signing.key"] = System.getenv('SIGNING_KEY')
7 |
8 | nexusPublishing {
9 | repositories {
10 | sonatype {
11 | stagingProfileId = sonatypeStagingProfileId
12 | username = ossrhUsername
13 | password = ossrhPassword
14 | nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/"))
15 | snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/"))
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/sample/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 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/src/main/java/com/wada811/viewmodelsavedstatektx/property/SavedStateProperty.kt:
--------------------------------------------------------------------------------
1 | package com.wada811.viewmodelsavedstatektx.property
2 |
3 | import androidx.lifecycle.SavedStateHandle
4 | import androidx.lifecycle.ViewModel
5 | import kotlin.properties.ReadWriteProperty
6 | import kotlin.reflect.KProperty
7 |
8 | internal class SavedStateProperty(
9 | private val savedStateHandle: SavedStateHandle
10 | ) : ReadWriteProperty {
11 | @Suppress("RemoveExplicitTypeArguments", "UNCHECKED_CAST")
12 | override operator fun getValue(thisRef: ViewModel, property: KProperty<*>): T {
13 | return savedStateHandle.get(property.name) as T
14 | }
15 |
16 | override operator fun setValue(thisRef: ViewModel, property: KProperty<*>, value: T) {
17 | savedStateHandle[property.name] = value
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/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 |
--------------------------------------------------------------------------------
/.github/workflows/maven-publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to MavenCentral
2 |
3 | on:
4 | release:
5 | types: [ released ]
6 |
7 | jobs:
8 | publish:
9 | name: Publish to MavenCentral
10 | runs-on: ubuntu-latest
11 | steps:
12 | - name: Check out code
13 | uses: actions/checkout@v3
14 | - name: Set up JDK 11
15 | uses: actions/setup-java@v3
16 | with:
17 | distribution: adopt
18 | java-version: 11
19 |
20 | - name: Publish to MavenCentral
21 | run: ./gradlew --max-workers 1 publishReleasePublicationToMavenLocal publishReleasePublicationToSonatypeRepository closeAndReleaseSonatypeStagingRepository
22 | env:
23 | OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }}
24 | OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }}
25 | SONATYPE_STAGING_PROFILE_ID: ${{ secrets.SONATYPE_STAGING_PROFILE_ID }}
26 | SIGNING_KEY_ID: ${{ secrets.SIGNING_KEY_ID }}
27 | SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }}
28 | SIGNING_KEY: ${{ secrets.SIGNING_KEY }}
29 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/src/main/java/com/wada811/viewmodelsavedstatektx/property/SavedStateSerializableProperty.kt:
--------------------------------------------------------------------------------
1 | package com.wada811.viewmodelsavedstatektx.property
2 |
3 | import androidx.lifecycle.SavedStateHandle
4 | import androidx.lifecycle.ViewModel
5 | import com.wada811.viewmodelsavedstatektx.SavedStateAdapter
6 | import kotlin.properties.ReadWriteProperty
7 | import kotlin.reflect.KProperty
8 |
9 | internal class SavedStateSerializableProperty(
10 | private val savedStateHandle: SavedStateHandle,
11 | private val adapter: SavedStateAdapter
12 | ) : ReadWriteProperty {
13 | @Suppress("RemoveExplicitTypeArguments", "UNCHECKED_CAST")
14 | override operator fun getValue(thisRef: ViewModel, property: KProperty<*>): TValue {
15 | return adapter.fromSavedState(savedStateHandle.get(property.name) as TState)
16 | }
17 |
18 | override operator fun setValue(thisRef: ViewModel, property: KProperty<*>, value: TValue) {
19 | savedStateHandle[property.name] = adapter.toSavedState(value)
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/wada811/viewmodelsavedstatektx/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.wada811.viewmodelsavedstatektx.sample
2 |
3 | import android.content.Context
4 | import android.content.Intent
5 | import android.os.Bundle
6 | import android.os.Handler
7 | import androidx.appcompat.app.AppCompatActivity
8 | import java.util.concurrent.TimeUnit
9 |
10 | class MainActivity : AppCompatActivity() {
11 |
12 | companion object {
13 | private const val ACTION_RESTART = "ACTION_RESTART"
14 | @JvmStatic
15 | fun createIntent(context: Context): Intent = Intent(context, MainActivity::class.java).also {
16 | it.action = ACTION_RESTART
17 | it.flags = Intent.FLAG_ACTIVITY_NO_ANIMATION
18 | }
19 | }
20 |
21 | override fun onCreate(savedInstanceState: Bundle?) {
22 | super.onCreate(savedInstanceState)
23 | if (intent.action == ACTION_RESTART) {
24 | setContentView(R.layout.main_activity)
25 | Handler().postDelayed({
26 | finish()
27 | }, TimeUnit.SECONDS.toMillis(1))
28 | return
29 | }
30 | startActivity(SampleActivity.createIntent(this))
31 | finish()
32 | return
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-kapt'
4 |
5 | android {
6 | namespace "com.wada811.savedstateviewmodel.sample"
7 | compileSdkVersion 33
8 | defaultConfig {
9 | applicationId "com.wada811.savedstateviewmodel.sample"
10 | minSdkVersion 21
11 | targetSdkVersion 33
12 | }
13 | buildTypes {
14 | debug {
15 | minifyEnabled true
16 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
17 | }
18 | release {
19 | minifyEnabled true
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | kotlinOptions {
24 | jvmTarget = JavaVersion.VERSION_1_8
25 | }
26 | dataBinding {
27 | enabled = true
28 | }
29 | }
30 |
31 | dependencies {
32 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.9.10"
33 | implementation 'androidx.appcompat:appcompat:1.6.1'
34 | implementation 'androidx.activity:activity-ktx:1.7.2'
35 | implementation 'androidx.fragment:fragment-ktx:1.6.1'
36 | implementation project(':ViewModel-SavedState-ktx')
37 | implementation 'com.wada811.databindingktx:databindingktx:7.0.0'
38 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
39 | implementation 'com.google.android.material:material:1.9.0'
40 | }
41 |
--------------------------------------------------------------------------------
/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 | org.gradle.caching=true
15 | org.gradle.configureondemand=true
16 | # Kotlin code style for this project: "official" or "obsolete":
17 | kotlin.code.style=official
18 | # Compile avoidance for kapt
19 | kapt.include.compile.classpath=false
20 | # Incremental annotation processing in KAPT
21 | # https://blog.jetbrains.com/kotlin/2019/04/kotlin-1-3-30-released/
22 | kapt.incremental.apt=true
23 | # Incremental annotation processing for DataBinding
24 | # https://developer.android.com/studio/releases/gradle-plugin#incremental_ap
25 | android.databinding.incremental=true
26 | # AndroidX package structure to make it clearer which packages are bundled with the
27 | # Android operating system, and which are packaged with your app's APK
28 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
29 | android.useAndroidX=true
30 | # Automatically convert third-party libraries to use AndroidX
31 | #android.enableJetifier=true
32 | # Cacheable unit tests
33 | # https://developer.android.com/studio/releases/gradle-plugin#cacheable_tests
34 | android.testConfig.useRelativePath=true
35 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/src/main/java/com/wada811/viewmodelsavedstatektx/property/SavedStateLiveDataSerializableProperty.kt:
--------------------------------------------------------------------------------
1 | package com.wada811.viewmodelsavedstatektx.property
2 |
3 | import androidx.lifecycle.MediatorLiveData
4 | import androidx.lifecycle.MutableLiveData
5 | import androidx.lifecycle.SavedStateHandle
6 | import androidx.lifecycle.ViewModel
7 | import com.wada811.viewmodelsavedstatektx.SavedStateAdapter
8 | import kotlin.properties.ReadOnlyProperty
9 | import kotlin.reflect.KProperty
10 |
11 | internal class SavedStateLiveDataSerializableProperty(
12 | private val savedStateHandle: SavedStateHandle,
13 | private val adapter: SavedStateAdapter
14 | ) : ReadOnlyProperty> {
15 | private var savedStateLiveData: MutableLiveData? = null
16 |
17 | override fun getValue(thisRef: ViewModel, property: KProperty<*>): MutableLiveData {
18 | return savedStateLiveData ?: SavedStateSerializableLiveData(savedStateHandle, property.name, adapter).also {
19 | savedStateLiveData = it
20 | }
21 | }
22 |
23 | @Suppress("UNCHECKED_CAST")
24 | private class SavedStateSerializableLiveData(
25 | savedStateHandle: SavedStateHandle,
26 | key: String,
27 | private val adapter: SavedStateAdapter
28 | ) : MediatorLiveData() {
29 | private val liveData: MutableLiveData = savedStateHandle.getLiveData(key)
30 |
31 | init {
32 | value = adapter.fromSavedState(liveData.value as TState)
33 | addSource(liveData) {
34 | value = adapter.fromSavedState(it as TState)
35 | }
36 | }
37 |
38 | override fun getValue(): TValue {
39 | return adapter.fromSavedState(liveData.value as TState)
40 | }
41 |
42 | override fun setValue(value: TValue) {
43 | super.setValue(value)
44 | val stateValue = adapter.toSavedState(value)
45 | if (liveData.value != stateValue) {
46 | @Suppress("USELESS_CAST")
47 | liveData.value = stateValue as TState
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/wada811/viewmodelsavedstatektx/sample/SampleViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.wada811.viewmodelsavedstatektx.sample
2 |
3 | import androidx.lifecycle.LiveData
4 | import androidx.lifecycle.MediatorLiveData
5 | import androidx.lifecycle.MutableLiveData
6 | import androidx.lifecycle.SavedStateHandle
7 | import androidx.lifecycle.ViewModel
8 | import com.wada811.viewmodelsavedstatektx.SavedStateAdapter
9 | import com.wada811.viewmodelsavedstatektx.liveData
10 | import com.wada811.viewmodelsavedstatektx.sample.SampleViewModel.CountUpValue.ONE
11 |
12 | class SampleViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
13 | enum class CountUpValue(val count: Int) {
14 | ONE(1),
15 | TEN(10)
16 | }
17 |
18 | private var viewModelCount = MutableLiveData(0)
19 | var viewModelCountText: LiveData = MediatorLiveData().also { liveData ->
20 | liveData.addSource(viewModelCount) { count ->
21 | liveData.value = "$count"
22 | }
23 | }
24 | val countUpValueEnumLiveData: MutableLiveData by savedStateHandle.liveData(object : SavedStateAdapter {
25 | override fun toSavedState(value: CountUpValue?): Int? = value?.ordinal
26 | override fun fromSavedState(state: Int?): CountUpValue? = CountUpValue.values().firstOrNull { it.ordinal == state }
27 | }, ONE)
28 | val savedStateCount: MutableLiveData by savedStateHandle.liveData(0)
29 | var savedStateCountText: LiveData = MediatorLiveData().also { liveData ->
30 | liveData.addSource(savedStateCount) { count ->
31 | liveData.value = "$count"
32 | }
33 | }
34 |
35 | val log: MutableLiveData by savedStateHandle.liveData("Log:")
36 |
37 | init {
38 | appendLog("ViewModel::init")
39 | }
40 |
41 | fun countUp() {
42 | viewModelCount.value = viewModelCount.value?.plus(countUpValueEnumLiveData.value?.count ?: 0)
43 | savedStateCount.value = savedStateCount.value?.plus(countUpValueEnumLiveData.value?.count ?: 0)
44 | }
45 |
46 | fun appendLog(text: String) {
47 | log.value = log.value!!.lines().toMutableList().also { it.add(text) }.takeLast(10).joinToString("\n")
48 | }
49 |
50 | override fun onCleared() {
51 | super.onCleared()
52 | appendLog("ViewModel::onCleared")
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/publish-module.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'maven-publish'
2 | apply plugin: 'signing'
3 |
4 | ext {
5 | PUBLISH_GROUP_ID = 'com.wada811.viewmodelsavedstatektx'
6 | PUBLISH_ARTIFACT_ID = 'viewmodelsavedstatektx'
7 | PUBLISH_VERSION = '3.0.0'
8 | }
9 |
10 | android {
11 | publishing {
12 | singleVariant('release') {
13 | withSourcesJar()
14 | }
15 | }
16 | }
17 |
18 | signing {
19 | useInMemoryPgpKeys(
20 | rootProject.ext["signing.keyId"],
21 | rootProject.ext["signing.key"],
22 | rootProject.ext["signing.password"],
23 | )
24 | sign publishing.publications
25 | }
26 |
27 | group = PUBLISH_GROUP_ID
28 | version = PUBLISH_VERSION
29 |
30 | afterEvaluate {
31 | publishing {
32 | publications {
33 | release(MavenPublication) {
34 | groupId PUBLISH_GROUP_ID
35 | artifactId PUBLISH_ARTIFACT_ID
36 | version PUBLISH_VERSION
37 |
38 | // Two artifacts, the `aar` (or `jar`) and the sources
39 | if (project.plugins.findPlugin("com.android.library")) {
40 | from components.release
41 | } else {
42 | from components.java
43 | }
44 |
45 | pom {
46 | name = PUBLISH_ARTIFACT_ID
47 | description = 'ViewModel-SavedState-ktx make easy handling saved state by delegated property.'
48 | url = 'https://github.com/wada811/ViewModel-SavedState-ktx'
49 |
50 | licenses {
51 | license {
52 | name = 'The Apache License, Version 2.0'
53 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
54 | }
55 | }
56 | developers {
57 | developer {
58 | id = 'wada811'
59 | name = 'WADA Takumi'
60 | email = 'at.wada811@gmail.com'
61 | }
62 | }
63 | scm {
64 | connection = 'scm:git:github.com/wada811/ViewModel-SavedState-ktx.git'
65 | developerConnection = 'scm:git:ssh://github.com/wada811/ViewModel-SavedState-ktx.git'
66 | url = 'https://github.com/wada811/ViewModel-SavedState-ktx/tree/master'
67 | }
68 | }
69 | }
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/src/main/java/com/wada811/viewmodelsavedstatektx/SavedStateHandles.kt:
--------------------------------------------------------------------------------
1 | package com.wada811.viewmodelsavedstatektx
2 |
3 | import androidx.lifecycle.MutableLiveData
4 | import androidx.lifecycle.SavedStateHandle
5 | import androidx.lifecycle.ViewModel
6 | import com.wada811.viewmodelsavedstatektx.property.SavedStateLiveDataProperty
7 | import com.wada811.viewmodelsavedstatektx.property.SavedStateLiveDataSerializableProperty
8 | import com.wada811.viewmodelsavedstatektx.property.SavedStateProperty
9 | import com.wada811.viewmodelsavedstatektx.property.SavedStateSerializableProperty
10 | import kotlin.properties.PropertyDelegateProvider
11 | import kotlin.properties.ReadOnlyProperty
12 | import kotlin.properties.ReadWriteProperty
13 | import kotlin.reflect.KProperty
14 |
15 | fun SavedStateHandle.property(): ReadWriteProperty = SavedStateProperty(this)
16 | fun SavedStateHandle.property(defaultValue: T): PropertyDelegateProvider> {
17 | return PropertyDelegateProvider { _: ViewModel, property: KProperty<*> ->
18 | if (!this.contains(property.name)) {
19 | this[property.name] = defaultValue
20 | }
21 | property()
22 | }
23 | }
24 |
25 | fun SavedStateHandle.property(adapter: SavedStateAdapter): ReadWriteProperty = SavedStateSerializableProperty(this, adapter)
26 | fun SavedStateHandle.property(adapter: SavedStateAdapter, defaultValue: TValue): PropertyDelegateProvider> {
27 | return PropertyDelegateProvider { _: ViewModel, property: KProperty<*> ->
28 | if (!this.contains(property.name)) {
29 | this[property.name] = adapter.toSavedState(defaultValue)
30 | }
31 | property(adapter)
32 | }
33 | }
34 |
35 | fun SavedStateHandle.liveData(): ReadOnlyProperty> = SavedStateLiveDataProperty(this)
36 | fun SavedStateHandle.liveData(defaultValue: T): PropertyDelegateProvider>> {
37 | return PropertyDelegateProvider { _: ViewModel, property: KProperty<*> ->
38 | if (!this.contains(property.name)) {
39 | this[property.name] = defaultValue
40 | }
41 | liveData()
42 | }
43 | }
44 |
45 | fun SavedStateHandle.liveData(adapter: SavedStateAdapter): ReadOnlyProperty> = SavedStateLiveDataSerializableProperty(this, adapter)
46 | fun SavedStateHandle.liveData(adapter: SavedStateAdapter, defaultValue: TValue): PropertyDelegateProvider>> {
47 | return PropertyDelegateProvider { _: ViewModel, property: KProperty<*> ->
48 | if (!this.contains(property.name)) {
49 | this[property.name] = adapter.toSavedState(defaultValue)
50 | }
51 | liveData(adapter)
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
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 %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 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 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/src/main/java/com/wada811/viewmodelsavedstatektx/extension/Intent.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("unused")
2 |
3 | package com.wada811.viewmodelsavedstatektx.extension
4 |
5 | import android.content.Intent
6 | import android.os.Bundle
7 | import android.os.Parcelable
8 | import java.io.Serializable
9 | import kotlin.reflect.KProperty
10 |
11 | fun Intent.putExtra(property: KProperty<*>, value: Boolean) = this.putExtra(property.name, value)
12 | fun Intent.putExtra(property: KProperty<*>, value: BooleanArray) = this.putExtra(property.name, value)
13 | fun Intent.putExtra(property: KProperty<*>, value: Double) = this.putExtra(property.name, value)
14 | fun Intent.putExtra(property: KProperty<*>, value: DoubleArray) = this.putExtra(property.name, value)
15 | fun Intent.putExtra(property: KProperty<*>, value: Int) = this.putExtra(property.name, value)
16 | fun Intent.putExtra(property: KProperty<*>, value: IntArray) = this.putExtra(property.name, value)
17 | fun Intent.putExtra(property: KProperty<*>, value: Long) = this.putExtra(property.name, value)
18 | fun Intent.putExtra(property: KProperty<*>, value: LongArray) = this.putExtra(property.name, value)
19 | fun Intent.putExtra(property: KProperty<*>, value: String) = this.putExtra(property.name, value)
20 | fun Intent.putExtra(property: KProperty<*>, value: Array) = this.putExtra(property.name, value)
21 | fun Intent.putExtra(property: KProperty<*>, value: Array) = this.putExtra(property.name, value)
22 | fun Intent.putExtra(property: KProperty<*>, value: Array) = this.putExtra(property.name, value)
23 | fun Intent.putExtra(property: KProperty<*>, value: Bundle) = this.putExtra(property.name, value)
24 | fun Intent.putExtra(property: KProperty<*>, value: Byte) = this.putExtra(property.name, value)
25 | fun Intent.putExtra(property: KProperty<*>, value: ByteArray) = this.putExtra(property.name, value)
26 | fun Intent.putExtra(property: KProperty<*>, value: Char) = this.putExtra(property.name, value)
27 | fun Intent.putExtra(property: KProperty<*>, value: CharArray) = this.putExtra(property.name, value)
28 | fun Intent.putExtra(property: KProperty<*>, value: CharSequence) = this.putExtra(property.name, value)
29 | fun Intent.putExtra(property: KProperty<*>, value: Float) = this.putExtra(property.name, value)
30 | fun Intent.putExtra(property: KProperty<*>, value: FloatArray) = this.putExtra(property.name, value)
31 | fun Intent.putExtra(property: KProperty<*>, value: Parcelable) = this.putExtra(property.name, value)
32 | fun Intent.putExtra(property: KProperty<*>, value: Serializable) = this.putExtra(property.name, value)
33 | fun Intent.putExtra(property: KProperty<*>, value: Short) = this.putExtra(property.name, value)
34 | fun Intent.putExtra(property: KProperty<*>, value: ShortArray) = this.putExtra(property.name, value)
35 | fun Intent.putIntegerArrayListExtra(property: KProperty<*>, value: ArrayList) = this.putIntegerArrayListExtra(property.name, value)
36 | fun Intent.putStringArrayListExtra(property: KProperty<*>, value: ArrayList) = this.putStringArrayListExtra(property.name, value)
37 | fun Intent.putCharSequenceArrayListExtra(property: KProperty<*>, value: ArrayList) = this.putCharSequenceArrayListExtra(property.name, value)
38 | fun Intent.putParcelableArrayListExtra(property: KProperty<*>, value: ArrayList) = this.putParcelableArrayListExtra(property.name, value)
39 |
--------------------------------------------------------------------------------
/ViewModel-SavedState-ktx/src/main/java/com/wada811/viewmodelsavedstatektx/extension/Bundle.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("unused")
2 |
3 | package com.wada811.viewmodelsavedstatektx.extension
4 |
5 | import android.os.Bundle
6 | import android.os.Parcelable
7 | import java.io.Serializable
8 | import kotlin.reflect.KProperty
9 |
10 | fun Bundle.putBoolean(property: KProperty<*>, value: Boolean) = this.putBoolean(property.name, value)
11 | fun Bundle.putBooleanArray(property: KProperty<*>, value: BooleanArray) = this.putBooleanArray(property.name, value)
12 | fun Bundle.putDouble(property: KProperty<*>, value: Double) = this.putDouble(property.name, value)
13 | fun Bundle.putDoubleArray(property: KProperty<*>, value: DoubleArray) = this.putDoubleArray(property.name, value)
14 | fun Bundle.putInt(property: KProperty<*>, value: Int) = this.putInt(property.name, value)
15 | fun Bundle.putIntArray(property: KProperty<*>, value: IntArray) = this.putIntArray(property.name, value)
16 | fun Bundle.putLong(property: KProperty<*>, value: Long) = this.putLong(property.name, value)
17 | fun Bundle.putLongArray(property: KProperty<*>, value: LongArray) = this.putLongArray(property.name, value)
18 | fun Bundle.putString(property: KProperty<*>, value: String) = this.putString(property.name, value)
19 | fun Bundle.putStringArray(property: KProperty<*>, value: Array) = this.putStringArray(property.name, value)
20 | fun Bundle.putCharSequenceArray(property: KProperty<*>, value: Array) = this.putCharSequenceArray(property.name, value)
21 | fun Bundle.putParcelableArray(property: KProperty<*>, value: Array) = this.putParcelableArray(property.name, value)
22 | fun Bundle.putBundle(property: KProperty<*>, value: Bundle) = this.putBundle(property.name, value)
23 | fun Bundle.putByte(property: KProperty<*>, value: Byte) = this.putByte(property.name, value)
24 | fun Bundle.putByteArray(property: KProperty<*>, value: ByteArray) = this.putByteArray(property.name, value)
25 | fun Bundle.putChar(property: KProperty<*>, value: Char) = this.putChar(property.name, value)
26 | fun Bundle.putCharArray(property: KProperty<*>, value: CharArray) = this.putCharArray(property.name, value)
27 | fun Bundle.putCharSequence(property: KProperty<*>, value: CharSequence) = this.putCharSequence(property.name, value)
28 | fun Bundle.putFloat(property: KProperty<*>, value: Float) = this.putFloat(property.name, value)
29 | fun Bundle.putFloatArray(property: KProperty<*>, value: FloatArray) = this.putFloatArray(property.name, value)
30 | fun Bundle.putParcelable(property: KProperty<*>, value: Parcelable) = this.putParcelable(property.name, value)
31 | fun Bundle.putSerializable(property: KProperty<*>, value: Serializable) = this.putSerializable(property.name, value)
32 | fun Bundle.putShort(property: KProperty<*>, value: Short) = this.putShort(property.name, value)
33 | fun Bundle.putShortArray(property: KProperty<*>, value: ShortArray) = this.putShortArray(property.name, value)
34 | fun Bundle.putIntegerArrayList(property: KProperty<*>, value: ArrayList) = this.putIntegerArrayList(property.name, value)
35 | fun Bundle.putStringArrayList(property: KProperty<*>, value: ArrayList) = this.putStringArrayList(property.name, value)
36 | fun Bundle.putCharSequenceArrayList(property: KProperty<*>, value: ArrayList) = this.putCharSequenceArrayList(property.name, value)
37 | fun Bundle.putParcelableArrayList(property: KProperty<*>, value: ArrayList) = this.putParcelableArrayList(property.name, value)
38 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/wada811/viewmodelsavedstatektx/sample/SampleActivity.kt:
--------------------------------------------------------------------------------
1 | package com.wada811.viewmodelsavedstatektx.sample
2 |
3 | import android.content.Context
4 | import android.content.Intent
5 | import android.content.pm.ActivityInfo
6 | import android.os.Bundle
7 | import android.provider.Settings
8 | import android.widget.Toast
9 | import androidx.activity.viewModels
10 | import androidx.appcompat.app.AppCompatActivity
11 | import com.wada811.databinding.dataBinding
12 | import com.wada811.viewmodelsavedstatektx.extension.putExtra
13 | import com.wada811.viewmodelsavedstatektx.sample.SampleViewModel.CountUpValue
14 | import com.wada811.viewmodelsavedstatektx.sample.SampleViewModel.CountUpValue.ONE
15 | import com.wada811.viewmodelsavedstatektx.sample.SampleViewModel.CountUpValue.TEN
16 | import com.wada811.viewmodelsavedstatektx.sample.databinding.SampleActivityBinding
17 |
18 | class SampleActivity : AppCompatActivity(R.layout.sample_activity) {
19 | private val binding: SampleActivityBinding by dataBinding()
20 | private val viewModel: SampleViewModel by viewModels()
21 | private var count = 0
22 |
23 | override fun onCreate(savedInstanceState: Bundle?) {
24 | super.onCreate(savedInstanceState)
25 | viewModel.appendLog("Activity::onCreate")
26 | binding.viewModel = viewModel
27 | binding.activityCountText.text = "$count"
28 | binding.countUpButton.setOnClickListener {
29 | count += viewModel.countUpValueEnumLiveData.value?.count ?: 0
30 | binding.activityCountText.text = "$count"
31 | viewModel.countUp()
32 | }
33 | when (viewModel.countUpValueEnumLiveData.value) {
34 | ONE -> binding.plusOneButton.isChecked = true
35 | TEN -> binding.plusTenButton.isChecked = true
36 | null -> Unit
37 | }
38 | binding.plusOneButton.setOnCheckedChangeListener { _, isChecked ->
39 | if (isChecked) {
40 | binding.plusTenButton.isChecked = false
41 | }
42 | viewModel.countUpValueEnumLiveData.value = if (isChecked) CountUpValue.ONE else null
43 | }
44 | binding.plusTenButton.setOnCheckedChangeListener { _, isChecked ->
45 | if (isChecked) {
46 | binding.plusOneButton.isChecked = false
47 | }
48 | viewModel.countUpValueEnumLiveData.value = if (isChecked) CountUpValue.TEN else null
49 | }
50 | binding.rotateButton.setOnClickListener {
51 | viewModel.appendLog("Activity::rotate")
52 | requestedOrientation = when (requestedOrientation) {
53 | ActivityInfo.SCREEN_ORIENTATION_PORTRAIT -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
54 | else -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
55 | }
56 | }
57 | binding.restartButton.setOnClickListener {
58 | if (isEnabledDoNotKeepActivities()) {
59 | viewModel.appendLog("Activity::restart")
60 | startActivity(MainActivity.createIntent(this))
61 | } else {
62 | Toast.makeText(this, "adb shell settings put global always_finish_activities 1", Toast.LENGTH_LONG).show()
63 | }
64 | }
65 | }
66 |
67 | private fun isEnabledDoNotKeepActivities(): Boolean {
68 | val doNotKeepActivities = Settings.Global.getInt(contentResolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0)
69 | return doNotKeepActivities != 0
70 | }
71 |
72 | override fun onPause() {
73 | super.onPause()
74 | viewModel.appendLog("Activity::onPause")
75 | }
76 |
77 | override fun onResume() {
78 | super.onResume()
79 | viewModel.appendLog("Activity::onResume")
80 | }
81 |
82 | override fun onDestroy() {
83 | super.onDestroy()
84 | viewModel.appendLog("Activity::onDestroy")
85 | }
86 |
87 | companion object {
88 | @JvmStatic
89 | fun createIntent(context: Context): Intent = Intent(context, SampleActivity::class.java).also {
90 | it.putExtra(SampleViewModel::savedStateCount, 0)
91 | }
92 | }
93 | }
94 |
95 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ViewModel-SavedState-ktx
2 | =====
3 |
4 | `ViewModel-SavedState-ktx` make easy handling saved state by delegated property.
5 |
6 | ## Overview
7 |
8 | `ViewModel-SavedState-ktx` is kotlin extensions of [Saved State module for ViewModel](https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate).
9 |
10 | ### What is ViewModel-SavedState
11 |
12 | Up to now, UI states is usually stored in `onSavedInstanceState` and restored in `onCreate`. From now on, you can store and restore UI states by SavedStateHandle using ViewModel-SavedState.
13 |
14 | ### Why use ViewModel-SavedState
15 |
16 | ViewModel has been kept alive when configuration changes occurred, but ViewModel has been destroyed when Activity killed by OS. By using ViewModel-SavedState, ViewModel save its property when Activity
17 | killed by OS.
18 |
19 | ### How to use ViewModel-SavedState
20 |
21 | #### How to get SavedStateHandle
22 |
23 | - You can get a SavedStateHandle instance via ViewModel's constructor.
24 |
25 | #### How to pass SavedStateHandle to ViewModel constructor
26 |
27 | - If you call `by viewModels()` in Activity or Fragment, `SavedStateHandle` is automatically passed.
28 | - The `intent.extra` or `arguments` is passed automatically to `SavedStateHandle`.
29 | - If you want to pass parameters other than `SavedStateHandle` or `Application, SavedStateHandle` into ViewModel's constructor, you pass a ViewModel's factory into `by viewModels`.
30 | - The ViewModel's factory needs to extend `AbstractSavedStateViewModelFactory`.
31 | - The `intent.extra` or `arguments` needs to pass manually to the ViewModel's factory if need it.
32 |
33 | #### How to use SavedStateHandle
34 |
35 | - You can use a value by `SavedStateHandle#get(key)` and `SavedStateHandle#set(key, value)`
36 | - The value is initialized by value of same key in `intent.extra` or `arguments`.
37 | - You can use a LiveData instance by `SavedStateHandle#getLiveData(key)`
38 | - If you change the LiveData instance's value, a value of SavedStateHandle is changed.
39 |
40 | ### Problems in ViewModel-SavedState
41 |
42 | - If you get a value by `SavedStateHandle#get(key)`, you don't only change the value but also need to call `SavedStateHandle#set(key, value)`.
43 | - `SavedStateHandle` requires a key to use.
44 | - The key needs to be same as a key of `intent.extra` or `arguments`.
45 | - `SavedStateHandle` has restrictions on available types.
46 |
47 | ### Solutions by ViewModel-SavedState-ktx
48 |
49 | - When you change the value, `SavedStateHandle#set(key, value)` is automatically called by Delegated Properties.
50 | - ViewModel-SavedState-ktx don't requires a key to use `SavedStateHandle`. Instead, it uses property name.
51 | - It provides extension methods for specifying property name in `Intent` and `Bundle`.
52 | - You can use any type using `SavedStateAdapter` that converts between the type used in `SavedStateHandle` and the type actually used in `ViewModel`.
53 |
54 | ## Usage
55 |
56 | You can pass parameters of `Intent` or `Bundle` to ViewModel property by extension methods using its property reference.
57 |
58 | ```kotlin
59 | class SampleActivity : AppCompatActivity(R.layout.sample_activity) {
60 | private val viewModel: SampleViewModel by viewModels()
61 |
62 | companion object {
63 | @JvmStatic
64 | fun createIntent(context: Context): Intent = Intent(context, SampleActivity::class.java).also {
65 | it.putExtra(SampleViewModel::text, "sample")
66 | }
67 | }
68 | }
69 | ```
70 |
71 | You can get a value or a LiveData instance by delegated property using SavedStateHandle's extension methods.
72 |
73 | ```kotlin
74 | class SampleViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
75 | val text: String by savedStateHandle.property()
76 | val count: MutableLiveData by savedStateHandle.liveData(defaultValue = 0)
77 | val timeUnit: MutableLiveData by savedStateHandle.liveData(object : SavedStateAdapter {
78 | override fun toSavedState(value: TimeUnit?): Int? = value?.ordinal
79 | override fun fromSavedState(state: Int?): TimeUnit? = state?.let { TimeUnit.values()[it] }
80 | })
81 | }
82 | ```
83 |
84 | ## Gradle
85 |
86 | [](https://maven-badges.herokuapp.com/maven-central/com.wada811.viewmodelsavedstatektx/viewmodelsavedstatektx)
87 |
88 | ```groovy
89 | repositories {
90 | mavenCentral()
91 | }
92 |
93 | dependencies {
94 | implementation 'com.wada811.viewmodelsavedstatektx:viewmodelsavedstatektx:x.y.z'
95 | }
96 | ```
97 |
98 | ## Migrations
99 |
100 | ### 3.0.0
101 |
102 | #### dependencies
103 |
104 | ```diff
105 | - implementation 'com.github.wada811:ViewModel-SavedState-ktx:x.y.z'
106 | + implementation 'com.wada811.viewmodelsavedstatektx:viewmodelsavedstatektx:x.y.z'
107 | ```
108 |
109 | #### package
110 |
111 | ```diff
112 | -import com.wada811.viewmodelsavedstate
113 | +import com.wada811.viewmodelsavedstatektx
114 | ```
115 |
116 | ## License
117 |
118 | Copyright (C) 2019 wada811
119 |
120 | Licensed under the Apache License, Version 2.0
121 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/macos,android,intellij+iml,androidstudio
3 | # Edit at https://www.gitignore.io/?templates=macos,android,intellij+iml,androidstudio
4 |
5 | ### Android ###
6 | # Built application files
7 | *.apk
8 | *.ap_
9 | *.aab
10 |
11 | # Files for the ART/Dalvik VM
12 | *.dex
13 |
14 | # Java class files
15 | *.class
16 |
17 | # Generated files
18 | bin/
19 | gen/
20 | out/
21 |
22 | # Gradle files
23 | .gradle/
24 | build/
25 |
26 | # Local configuration file (sdk path, etc)
27 | local.properties
28 |
29 | # Proguard folder generated by Eclipse
30 | proguard/
31 |
32 | # Log Files
33 | *.log
34 |
35 | # Android Studio Navigation editor temp files
36 | .navigation/
37 |
38 | # Android Studio captures folder
39 | captures/
40 |
41 | # IntelliJ
42 | *.iml
43 | .idea/*
44 |
45 | # Keystore files
46 | # Uncomment the following lines if you do not want to check your keystore files in.
47 | #*.jks
48 | #*.keystore
49 |
50 | # External native build folder generated in Android Studio 2.2 and later
51 | .externalNativeBuild
52 |
53 | # Google Services (e.g. APIs or Firebase)
54 | google-services.json
55 |
56 | # Freeline
57 | freeline.py
58 | freeline/
59 | freeline_project_description.json
60 |
61 | # fastlane
62 | fastlane/report.xml
63 | fastlane/Preview.html
64 | fastlane/screenshots
65 | fastlane/test_output
66 | fastlane/readme.md
67 |
68 | ### Android Patch ###
69 | gen-external-apklibs
70 |
71 | ### AndroidStudio ###
72 | # Covers files to be ignored for android development using Android Studio.
73 |
74 | # Built application files
75 |
76 | # Files for the ART/Dalvik VM
77 |
78 | # Java class files
79 |
80 | # Generated files
81 |
82 | # Gradle files
83 | .gradle
84 |
85 | # Signing files
86 | .signing/
87 |
88 | # Local configuration file (sdk path, etc)
89 |
90 | # Proguard folder generated by Eclipse
91 |
92 | # Log Files
93 |
94 | # Android Studio
95 | /*/build/
96 | /*/local.properties
97 | /*/out
98 | /*/*/build
99 | /*/*/production
100 | *.ipr
101 | *~
102 | *.swp
103 |
104 | # Android Patch
105 |
106 | # External native build folder generated in Android Studio 2.2 and later
107 |
108 | # NDK
109 | obj/
110 |
111 | # IntelliJ IDEA
112 | *.iws
113 | /out/
114 |
115 | # User-specific configurations
116 | .idea/caches/
117 | .idea/libraries/
118 | .idea/shelf/
119 | .idea/.name
120 | .idea/compiler.xml
121 | .idea/copyright/profiles_settings.xml
122 | .idea/encodings.xml
123 | .idea/misc.xml
124 | .idea/modules.xml
125 | .idea/scopes/scope_settings.xml
126 | .idea/vcs.xml
127 | .idea/jsLibraryMappings.xml
128 | .idea/datasources.xml
129 | .idea/dataSources.ids
130 | .idea/sqlDataSources.xml
131 | .idea/dynamic.xml
132 | .idea/uiDesigner.xml
133 |
134 | # OS-specific files
135 | .DS_Store
136 | .DS_Store?
137 | ._*
138 | .Spotlight-V100
139 | .Trashes
140 | ehthumbs.db
141 | Thumbs.db
142 |
143 | # Legacy Eclipse project files
144 | .classpath
145 | .project
146 | .cproject
147 | .settings/
148 |
149 | # Mobile Tools for Java (J2ME)
150 | .mtj.tmp/
151 |
152 | # Package Files #
153 | *.war
154 | *.ear
155 |
156 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
157 | hs_err_pid*
158 |
159 | ## Plugin-specific files:
160 |
161 | # mpeltonen/sbt-idea plugin
162 | .idea_modules/
163 |
164 | # JIRA plugin
165 | atlassian-ide-plugin.xml
166 |
167 | # Mongo Explorer plugin
168 | .idea/mongoSettings.xml
169 |
170 | # Crashlytics plugin (for Android Studio and IntelliJ)
171 | com_crashlytics_export_strings.xml
172 | crashlytics.properties
173 | crashlytics-build.properties
174 | fabric.properties
175 |
176 | ### AndroidStudio Patch ###
177 |
178 | !/gradle/wrapper/gradle-wrapper.jar
179 |
180 | ### Intellij+iml ###
181 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
182 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
183 |
184 | # User-specific stuff
185 | .idea/**/workspace.xml
186 | .idea/**/tasks.xml
187 | .idea/**/usage.statistics.xml
188 | .idea/**/dictionaries
189 | .idea/**/shelf
190 |
191 | # Generated files
192 | .idea/**/contentModel.xml
193 |
194 | # Sensitive or high-churn files
195 | .idea/**/dataSources/
196 | .idea/**/dataSources.ids
197 | .idea/**/dataSources.local.xml
198 | .idea/**/sqlDataSources.xml
199 | .idea/**/dynamic.xml
200 | .idea/**/uiDesigner.xml
201 | .idea/**/dbnavigator.xml
202 |
203 | # Gradle
204 | .idea/**/gradle.xml
205 | .idea/**/libraries
206 |
207 | # Gradle and Maven with auto-import
208 | # When using Gradle or Maven with auto-import, you should exclude module files,
209 | # since they will be recreated, and may cause churn. Uncomment if using
210 | # auto-import.
211 | # .idea/modules.xml
212 | # .idea/*.iml
213 | # .idea/modules
214 |
215 | # CMake
216 | cmake-build-*/
217 |
218 | # Mongo Explorer plugin
219 | .idea/**/mongoSettings.xml
220 |
221 | # File-based project format
222 |
223 | # IntelliJ
224 |
225 | # mpeltonen/sbt-idea plugin
226 |
227 | # JIRA plugin
228 |
229 | # Cursive Clojure plugin
230 | .idea/replstate.xml
231 |
232 | # Crashlytics plugin (for Android Studio and IntelliJ)
233 |
234 | # Editor-based Rest Client
235 | .idea/httpRequests
236 |
237 | # Android studio 3.1+ serialized cache file
238 | .idea/caches/build_file_checksums.ser
239 |
240 | ### Intellij+iml Patch ###
241 | # Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023
242 |
243 | modules.xml
244 |
245 | ### macOS ###
246 | # General
247 | .AppleDouble
248 | .LSOverride
249 |
250 | # Icon must end with two \r
251 | Icon
252 |
253 | # Thumbnails
254 |
255 | # Files that might appear in the root of a volume
256 | .DocumentRevisions-V100
257 | .fseventsd
258 | .TemporaryItems
259 | .VolumeIcon.icns
260 | .com.apple.timemachine.donotpresent
261 |
262 | # Directories potentially created on remote AFP share
263 | .AppleDB
264 | .AppleDesktop
265 | Network Trash Folder
266 | Temporary Items
267 | .apdisk
268 |
269 | # End of https://www.gitignore.io/api/macos,android,intellij+iml,androidstudio
270 |
271 | .envrc
272 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/sample_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
11 |
12 |
13 |
16 |
17 |
22 |
23 |
36 |
37 |
48 |
49 |
60 |
61 |
73 |
74 |
85 |
86 |
98 |
99 |
115 |
116 |
132 |
133 |
144 |
145 |
156 |
157 |
168 |
169 |
180 |
181 |
182 |
183 |
184 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
88 |
89 | # Use the maximum available, or set MAX_FD != -1 to use that value.
90 | MAX_FD=maximum
91 |
92 | warn () {
93 | echo "$*"
94 | } >&2
95 |
96 | die () {
97 | echo
98 | echo "$*"
99 | echo
100 | exit 1
101 | } >&2
102 |
103 | # OS specific support (must be 'true' or 'false').
104 | cygwin=false
105 | msys=false
106 | darwin=false
107 | nonstop=false
108 | case "$( uname )" in #(
109 | CYGWIN* ) cygwin=true ;; #(
110 | Darwin* ) darwin=true ;; #(
111 | MSYS* | MINGW* ) msys=true ;; #(
112 | NONSTOP* ) nonstop=true ;;
113 | esac
114 |
115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116 |
117 |
118 | # Determine the Java command to use to start the JVM.
119 | if [ -n "$JAVA_HOME" ] ; then
120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121 | # IBM's JDK on AIX uses strange locations for the executables
122 | JAVACMD=$JAVA_HOME/jre/sh/java
123 | else
124 | JAVACMD=$JAVA_HOME/bin/java
125 | fi
126 | if [ ! -x "$JAVACMD" ] ; then
127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
128 |
129 | Please set the JAVA_HOME variable in your environment to match the
130 | location of your Java installation."
131 | fi
132 | else
133 | JAVACMD=java
134 | if ! command -v java >/dev/null 2>&1
135 | then
136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 | fi
142 |
143 | # Increase the maximum file descriptors if we can.
144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145 | case $MAX_FD in #(
146 | max*)
147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148 | # shellcheck disable=SC3045
149 | MAX_FD=$( ulimit -H -n ) ||
150 | warn "Could not query maximum file descriptor limit"
151 | esac
152 | case $MAX_FD in #(
153 | '' | soft) :;; #(
154 | *)
155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156 | # shellcheck disable=SC3045
157 | ulimit -n "$MAX_FD" ||
158 | warn "Could not set maximum file descriptor limit to $MAX_FD"
159 | esac
160 | fi
161 |
162 | # Collect all arguments for the java command, stacking in reverse order:
163 | # * args from the command line
164 | # * the main class name
165 | # * -classpath
166 | # * -D...appname settings
167 | # * --module-path (only if needed)
168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169 |
170 | # For Cygwin or MSYS, switch paths to Windows format before running java
171 | if "$cygwin" || "$msys" ; then
172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174 |
175 | JAVACMD=$( cygpath --unix "$JAVACMD" )
176 |
177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
178 | for arg do
179 | if
180 | case $arg in #(
181 | -*) false ;; # don't mess with options #(
182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183 | [ -e "$t" ] ;; #(
184 | *) false ;;
185 | esac
186 | then
187 | arg=$( cygpath --path --ignore --mixed "$arg" )
188 | fi
189 | # Roll the args list around exactly as many times as the number of
190 | # args, so each arg winds up back in the position where it started, but
191 | # possibly modified.
192 | #
193 | # NB: a `for` loop captures its iteration list before it begins, so
194 | # changing the positional parameters here affects neither the number of
195 | # iterations, nor the values presented in `arg`.
196 | shift # remove old arg
197 | set -- "$@" "$arg" # push replacement arg
198 | done
199 | fi
200 |
201 |
202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204 |
205 | # Collect all arguments for the java command;
206 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
207 | # shell script including quotes and variable substitutions, so put them in
208 | # double quotes to make sure that they get re-expanded; and
209 | # * put everything else in single quotes, so that it's not re-expanded.
210 |
211 | set -- \
212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
213 | -classpath "$CLASSPATH" \
214 | org.gradle.wrapper.GradleWrapperMain \
215 | "$@"
216 |
217 | # Stop when "xargs" is not available.
218 | if ! command -v xargs >/dev/null 2>&1
219 | then
220 | die "xargs is not available"
221 | fi
222 |
223 | # Use "xargs" to parse quoted args.
224 | #
225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226 | #
227 | # In Bash we could simply go:
228 | #
229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230 | # set -- "${ARGS[@]}" "$@"
231 | #
232 | # but POSIX shell has neither arrays nor command substitution, so instead we
233 | # post-process each arg (as a line of input to sed) to backslash-escape any
234 | # character that might be a shell metacharacter, then use eval to reverse
235 | # that process (while maintaining the separation between arguments), and wrap
236 | # the whole thing up as a single "set" statement.
237 | #
238 | # This will of course break if any of these variables contains a newline or
239 | # an unmatched quote.
240 | #
241 |
242 | eval "set -- $(
243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244 | xargs -n1 |
245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246 | tr '\n' ' '
247 | )" '"$@"'
248 |
249 | exec "$JAVACMD" "$@"
250 |
--------------------------------------------------------------------------------
/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 2019 wada811
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------