├── docs
├── .nojekyll
├── index.html
└── README.md
├── sample
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── themes.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_main.xml
│ │ │ ├── values-night
│ │ │ │ └── themes.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── dylanc
│ │ │ │ └── mmkv
│ │ │ │ └── sample
│ │ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── dylanc
│ │ │ └── mmkv
│ │ │ └── sample
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── dylanc
│ │ └── mmkv
│ │ └── sample
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── library
├── .gitignore
├── consumer-rules.pro
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── dylanc
│ │ │ └── mmkv
│ │ │ ├── property
│ │ │ ├── MMKVProperty.kt
│ │ │ ├── MMKVLiveDataProperty.kt
│ │ │ ├── MMKVStateFlowProperty.kt
│ │ │ └── MMKVMapProperty.kt
│ │ │ ├── MMKVInitializer.kt
│ │ │ └── MMKVOwner.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── dylanc
│ │ └── mmkv
│ │ └── MMKVTest.kt
├── proguard-rules.pro
└── build.gradle
├── jitpack.yml
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── gradlew
├── README_ZH.md
├── README.md
└── LICENSE
/docs/.nojekyll:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/library/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk17
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = "MMKV-KTX"
2 | include ':sample'
3 | include ':library'
4 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | MMKV-KTX
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DylanCaiCoding/MMKV-KTX/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DylanCaiCoding/MMKV-KTX/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DylanCaiCoding/MMKV-KTX/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DylanCaiCoding/MMKV-KTX/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DylanCaiCoding/MMKV-KTX/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DylanCaiCoding/MMKV-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/DylanCaiCoding/MMKV-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/DylanCaiCoding/MMKV-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/DylanCaiCoding/MMKV-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/DylanCaiCoding/MMKV-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/DylanCaiCoding/MMKV-KTX/HEAD/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Jan 26 22:06:56 CST 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/sample/src/test/java/com/dylanc/mmkv/sample/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.dylanc.mmkv.sample
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 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/dylanc/mmkv/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.dylanc.mmkv.sample
2 |
3 | import android.os.Bundle
4 | import androidx.appcompat.app.AppCompatActivity
5 | import com.dylanc.mmkv.MMKVOwner
6 | import com.tencent.mmkv.MMKV
7 |
8 |
9 | class MainActivity : AppCompatActivity() {
10 |
11 | override fun onCreate(savedInstanceState: Bundle?) {
12 | super.onCreate(savedInstanceState)
13 | setContentView(R.layout.activity_main)
14 | val dir = filesDir.absolutePath + "/mmkv_2"
15 | MMKV.initialize(this, dir)
16 | }
17 | }
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
12 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/sample/src/androidTest/java/com/dylanc/mmkv/sample/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.dylanc.mmkv.sample
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.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.getInstrumentation().targetContext
22 | assertEquals("com.dylanc.mmkv.sample", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
--------------------------------------------------------------------------------
/library/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
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/sample/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/sample/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/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=-Xmx2048m -Dfile.encoding=UTF-8
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 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Document
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/library/src/main/java/com/dylanc/mmkv/property/MMKVProperty.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2024. Dylan Cai
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.dylanc.mmkv.property
18 |
19 | import com.dylanc.mmkv.IMMKVOwner
20 | import kotlin.properties.ReadWriteProperty
21 | import kotlin.reflect.KProperty
22 |
23 | class MMKVProperty(
24 | internal val decode: (String) -> V,
25 | internal val encode: Pair.() -> Boolean
26 | ) : ReadWriteProperty {
27 | override fun getValue(thisRef: IMMKVOwner, property: KProperty<*>): V =
28 | decode(property.name)
29 |
30 | override fun setValue(thisRef: IMMKVOwner, property: KProperty<*>, value: V) {
31 | encode((property.name) to value)
32 | }
33 | }
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'kotlin-android'
4 | id 'kotlin-parcelize'
5 | }
6 |
7 | android {
8 | compileSdkVersion buildConfig.compileSdkVersion
9 |
10 | defaultConfig {
11 | minSdkVersion buildConfig.minSdkVersion
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | consumerProguardFiles "consumer-rules.pro"
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 |
24 | compileOptions {
25 | sourceCompatibility JavaVersion.VERSION_1_8
26 | targetCompatibility JavaVersion.VERSION_1_8
27 | }
28 |
29 | kotlinOptions {
30 | jvmTarget = '1.8'
31 | freeCompilerArgs += ['-module-name', "mmkv-ktx"]
32 | }
33 | }
34 |
35 | dependencies {
36 | api "com.tencent:mmkv-static:$mmkvVersion"
37 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinVersion"
38 | implementation "androidx.startup:startup-runtime:$startupVersion"
39 | implementation "androidx.lifecycle:lifecycle-livedata-core-ktx:$lifecycleLivedataVersion"
40 | implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion"
41 | androidTestImplementation "androidx.test.ext:junit:$junitExtVersion"
42 | androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion"
43 | }
44 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'kotlin-android'
4 | }
5 |
6 | android {
7 | namespace "com.dylanc.mmkv.sample"
8 | compileSdk 34
9 |
10 | defaultConfig {
11 | applicationId "com.dylanc.mmkv.sample"
12 | minSdkVersion 23
13 | targetSdkVersion 34
14 | versionCode 1
15 | versionName "1.0"
16 |
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | compileOptions {
27 | sourceCompatibility JavaVersion.VERSION_1_8
28 | targetCompatibility JavaVersion.VERSION_1_8
29 | }
30 | kotlinOptions {
31 | jvmTarget = '1.8'
32 | }
33 | buildFeatures {
34 | viewBinding true
35 | }
36 | }
37 |
38 | dependencies {
39 | implementation 'androidx.core:core-ktx:1.6.0'
40 | implementation 'androidx.appcompat:appcompat:1.3.1'
41 | implementation 'com.google.android.material:material:1.4.0'
42 | implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
43 | implementation "androidx.startup:startup-runtime:1.1.0"
44 | implementation project(path: ':library')
45 | testImplementation 'junit:junit:4.13.2'
46 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
47 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
48 | }
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/library/src/main/java/com/dylanc/mmkv/property/MMKVLiveDataProperty.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2024. Dylan Cai
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.dylanc.mmkv.property
18 |
19 | import androidx.lifecycle.MutableLiveData
20 | import com.dylanc.mmkv.IMMKVOwner
21 | import kotlin.properties.ReadOnlyProperty
22 | import kotlin.reflect.KProperty
23 |
24 | class MMKVLiveDataProperty(private val mmkvProperty: MMKVProperty) : ReadOnlyProperty> {
25 | private var cache: MutableLiveData? = null
26 |
27 | override fun getValue(thisRef: IMMKVOwner, property: KProperty<*>): MutableLiveData =
28 | cache ?: MMKVLiveData(
29 | { mmkvProperty.getValue(thisRef, property) },
30 | { mmkvProperty.setValue(thisRef, property, it) }
31 | ).also { cache = it }
32 | }
33 |
34 | class MMKVLiveData(
35 | private val getMMKVValue: () -> V,
36 | private val setMMKVValue: (V) -> Unit
37 | ) : MutableLiveData(getMMKVValue()) {
38 | override fun getValue() = getMMKVValue()
39 |
40 | override fun setValue(value: V) {
41 | super.setValue(value)
42 | setMMKVValue(value)
43 | }
44 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/dylanc/mmkv/property/MMKVStateFlowProperty.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2024. Dylan Cai
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.dylanc.mmkv.property
18 |
19 | import com.dylanc.mmkv.IMMKVOwner
20 | import kotlinx.coroutines.flow.MutableStateFlow
21 | import kotlin.properties.ReadOnlyProperty
22 | import kotlin.reflect.KProperty
23 |
24 | class MMKVStateFlowProperty(private val mmkvProperty: MMKVProperty) : ReadOnlyProperty> {
25 | private var cache: MutableStateFlow? = null
26 |
27 | override fun getValue(thisRef: IMMKVOwner, property: KProperty<*>): MutableStateFlow =
28 | cache ?: MMKVFlow(
29 | { mmkvProperty.getValue(thisRef, property) },
30 | { mmkvProperty.setValue(thisRef, property, it) }
31 | ).also { cache = it }
32 | }
33 |
34 | class MMKVFlow(
35 | private val getMMKVValue: () -> V,
36 | private val setMMKVValue: (V) -> Unit,
37 | private val flow: MutableStateFlow = MutableStateFlow(getMMKVValue())
38 | ) : MutableStateFlow by flow {
39 | override var value: V
40 | get() = getMMKVValue()
41 | set(value) {
42 | val origin = flow.value
43 | flow.value = value
44 | if (origin != value) {
45 | setMMKVValue(value)
46 | }
47 | }
48 |
49 | override fun compareAndSet(expect: V, update: V): Boolean =
50 | flow.compareAndSet(expect, update).also { setSuccess ->
51 | if (setSuccess) setMMKVValue(update)
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/library/src/main/java/com/dylanc/mmkv/MMKVInitializer.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021. Dylan Cai
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | @file:Suppress("unused")
18 |
19 | package com.dylanc.mmkv
20 |
21 | import android.content.Context
22 | import android.content.pm.PackageManager
23 | import android.content.pm.PackageManager.GET_META_DATA
24 | import androidx.startup.Initializer
25 | import com.tencent.mmkv.MMKV
26 | import com.tencent.mmkv.MMKVLogLevel
27 |
28 | /**
29 | * Initialize MMKV by App startup. You can cancel the automatic initialization of MMKV.
30 | * If you want to change root directory or log level, you can add the following code to
31 | * the AndroidManifest.xml:
32 | *
33 | * ```xml
34 | *
37 | *
38 | *
41 | * ```
42 | *
43 | * @author Dylan Cai
44 | */
45 | class MMKVInitializer : Initializer {
46 |
47 | override fun create(context: Context) {
48 | val rootDir = context.filesDir.absolutePath + (getMetaData(context, "mmkv_root_dir") ?: "/mmkv")
49 | val logLevel = when (getMetaData(context, "mmkv_log_level")?.lowercase()) {
50 | "debug" -> MMKVLogLevel.LevelDebug
51 | "info" -> MMKVLogLevel.LevelInfo
52 | "warning" -> MMKVLogLevel.LevelWarning
53 | "error" -> MMKVLogLevel.LevelError
54 | "none" -> MMKVLogLevel.LevelNone
55 | else -> MMKVLogLevel.LevelInfo
56 | }
57 | MMKV.initialize(context, rootDir, logLevel)
58 | }
59 |
60 | private fun getMetaData(context: Context, key: String): String? =
61 | try {
62 | context.packageManager.getApplicationInfo(context.packageName, GET_META_DATA)
63 | .metaData?.getString(key)
64 | } catch (e: PackageManager.NameNotFoundException) {
65 | e.printStackTrace()
66 | null
67 | }
68 |
69 | override fun dependencies() = emptyList>>()
70 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/dylanc/mmkv/MMKVOwner.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2021. Dylan Cai
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.dylanc.mmkv
18 |
19 | import android.os.Parcelable
20 | import androidx.lifecycle.LiveData
21 | import com.dylanc.mmkv.property.MMKVLiveDataProperty
22 | import com.dylanc.mmkv.property.MMKVMapProperty
23 | import com.dylanc.mmkv.property.MMKVProperty
24 | import com.dylanc.mmkv.property.MMKVStateFlowProperty
25 | import com.tencent.mmkv.MMKV
26 | import kotlinx.coroutines.flow.StateFlow
27 | import kotlin.reflect.KProperty1
28 | import kotlin.reflect.full.memberProperties
29 | import kotlin.reflect.jvm.isAccessible
30 |
31 | open class MMKVOwner(override val mmapID: String) : IMMKVOwner {
32 | override val kv: MMKV by lazy { MMKV.mmkvWithID(mmapID) }
33 | }
34 |
35 | interface IMMKVOwner {
36 | val mmapID: String
37 |
38 | val kv: MMKV
39 |
40 | fun mmkvInt(default: Int = 0) =
41 | MMKVProperty({ kv.decodeInt(it, default) }, { kv.encode(first, second) })
42 |
43 | fun mmkvLong(default: Long = 0L) =
44 | MMKVProperty({ kv.decodeLong(it, default) }, { kv.encode(first, second) })
45 |
46 | fun mmkvBool(default: Boolean = false) =
47 | MMKVProperty({ kv.decodeBool(it, default) }, { kv.encode(first, second) })
48 |
49 | fun mmkvFloat(default: Float = 0f) =
50 | MMKVProperty({ kv.decodeFloat(it, default) }, { kv.encode(first, second) })
51 |
52 | fun mmkvDouble(default: Double = 0.0) =
53 | MMKVProperty({ kv.decodeDouble(it, default) }, { kv.encode(first, second) })
54 |
55 | fun mmkvString() =
56 | MMKVProperty({ kv.decodeString(it) }, { kv.encode(first, second) })
57 |
58 | fun mmkvString(default: String) =
59 | MMKVProperty({ kv.decodeString(it) ?: default }, { kv.encode(first, second) })
60 |
61 | fun mmkvStringSet() =
62 | MMKVProperty({ kv.decodeStringSet(it) }, { kv.encode(first, second) })
63 |
64 | fun mmkvStringSet(default: Set) =
65 | MMKVProperty({ kv.decodeStringSet(it) ?: default }, { kv.encode(first, second) })
66 |
67 | fun mmkvBytes() =
68 | MMKVProperty({ kv.decodeBytes(it) }, { kv.encode(first, second) })
69 |
70 | fun mmkvBytes(default: ByteArray) =
71 | MMKVProperty({ kv.decodeBytes(it) ?: default }, { kv.encode(first, second) })
72 |
73 | fun MMKVProperty.asLiveData() = MMKVLiveDataProperty(this)
74 |
75 | fun MMKVProperty.asStateFlow() = MMKVStateFlowProperty(this)
76 |
77 | fun MMKVProperty.asMap() = MMKVMapProperty(this)
78 |
79 | fun clearAllKV() = kv.clearAll()
80 | }
81 |
82 | inline fun IMMKVOwner.mmkvParcelable() =
83 | MMKVProperty({ kv.decodeParcelable(it, T::class.java) }, { kv.encode(first, second) })
84 |
85 | inline fun IMMKVOwner.mmkvParcelable(default: T) =
86 | MMKVProperty({ kv.decodeParcelable(it, T::class.java) ?: default }, { kv.encode(first, second) })
87 |
88 | fun IMMKVOwner.getAllKV(): Map = buildMap {
89 | val types = arrayOf(MMKVProperty::class, MMKVLiveDataProperty::class, MMKVStateFlowProperty::class, MMKVMapProperty::class)
90 | this@getAllKV::class.memberProperties
91 | .filterIsInstance>()
92 | .forEach { property ->
93 | property.isAccessible = true
94 | val delegate = property.getDelegate(this@getAllKV)
95 | if (types.any { it.isInstance(delegate) }) {
96 | this[property.name] = when (val value = property.get(this@getAllKV)) {
97 | is LiveData<*> -> value.value
98 | is StateFlow<*> -> value.value
99 | else -> value
100 | }
101 | }
102 | property.isAccessible = false
103 | }
104 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/library/src/main/java/com/dylanc/mmkv/property/MMKVMapProperty.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2024. Dylan Cai
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.dylanc.mmkv.property
18 |
19 | import android.os.Build
20 | import androidx.annotation.RequiresApi
21 | import com.dylanc.mmkv.IMMKVOwner
22 | import com.tencent.mmkv.MMKV
23 | import java.util.function.BiFunction
24 | import kotlin.properties.ReadOnlyProperty
25 | import kotlin.reflect.KProperty
26 |
27 | class MMKVMapProperty(
28 | private val mmkvProperty: MMKVProperty
29 | ) : ReadOnlyProperty> {
30 | private var cache: MMKVMap? = null
31 |
32 | override fun getValue(thisRef: IMMKVOwner, property: KProperty<*>): MutableMap =
33 | cache?.updateValues() ?: MMKVMap(thisRef.kv, property.name, mmkvProperty.decode, mmkvProperty.encode).also { cache = it }
34 | }
35 |
36 | class MMKVMap(
37 | private val kv: MMKV,
38 | private val propertyName: String,
39 | private val decode: (String) -> V,
40 | private val encode: Pair.() -> Boolean,
41 | private val map: MutableMap = mutableMapOf()
42 | ) : MutableMap by map {
43 | private val keysName = "$propertyName\$key"
44 |
45 | init {
46 | updateValues()
47 | }
48 |
49 | fun updateValues() = apply {
50 | map.clear()
51 | keys.forEach { key ->
52 | map[key] = decode(key.addPrefix())
53 | }
54 | }
55 |
56 | private fun String.addPrefix() = "$propertyName$$$this"
57 |
58 | override fun get(key: String): V? = decode(key.addPrefix())
59 |
60 | override fun put(key: String, value: V): V? =
61 | map.put(key, value).also {
62 | encode(key.addPrefix() to value)
63 | kv.encode(keysName, keys + key)
64 | }
65 |
66 | override fun putAll(from: Map) =
67 | map.putAll(from).also {
68 | from.forEach { (key, value) -> encode(key.addPrefix() to value) }
69 | kv.encode(keysName, keys + from.keys)
70 | }
71 |
72 | @RequiresApi(Build.VERSION_CODES.N)
73 | override fun putIfAbsent(key: String, value: V): V? {
74 | val isAbsent = map.containsKey(key).not()
75 | return map.putIfAbsent(key, value).also {
76 | if (isAbsent) {
77 | encode(key.addPrefix() to value)
78 | kv.encode(keysName, keys + key)
79 | }
80 | }
81 | }
82 |
83 | @RequiresApi(Build.VERSION_CODES.N)
84 | override fun merge(key: String, value: V & Any, remappingFunction: BiFunction): V? =
85 | map.merge(key, value, remappingFunction).also {
86 | if (it != null) {
87 | encode(key.addPrefix() to it)
88 | kv.encode(keysName, keys + key)
89 | }
90 | }
91 |
92 | override fun remove(key: String): V? =
93 | map.remove(key).also {
94 | kv.remove(key.addPrefix())
95 | kv.encode(keysName, keys - key)
96 | }
97 |
98 | @RequiresApi(Build.VERSION_CODES.N)
99 | override fun remove(key: String, value: V): Boolean =
100 | map.remove(key, value).also { removed ->
101 | if (removed) {
102 | kv.remove(key.addPrefix())
103 | kv.encode(keysName, keys - key)
104 | }
105 | }
106 |
107 | @RequiresApi(Build.VERSION_CODES.N)
108 | override fun replace(key: String, value: V): V? =
109 | map.replace(key, value).also {
110 | if (containsKey(key)) encode(key.addPrefix() to value)
111 | }
112 |
113 | @RequiresApi(Build.VERSION_CODES.N)
114 | override fun replace(key: String, oldValue: V, newValue: V): Boolean =
115 | map.replace(key, oldValue, newValue).also { replaced ->
116 | if (replaced) encode(key.addPrefix() to newValue)
117 | }
118 |
119 | @RequiresApi(Build.VERSION_CODES.N)
120 | override fun replaceAll(function: BiFunction) =
121 | map.replaceAll { key, value ->
122 | function.apply(key, value)
123 | .also { encode(key.addPrefix() to it) }
124 | }
125 |
126 | override fun clear() {
127 | keys.forEach { key -> kv.remove(key.addPrefix()) }
128 | kv.remove(keysName)
129 | map.clear()
130 | }
131 |
132 | override val keys: MutableSet
133 | get() = kv.decodeStringSet(keysName).orEmpty().toMutableSet()
134 |
135 | override val size: Int
136 | get() = keys.size
137 |
138 | override val entries: MutableSet>
139 | get() {
140 | val entries = map.entries
141 | return object : MutableSet> by entries {
142 |
143 | override fun iterator(): MutableIterator> {
144 | val iterator = entries.iterator()
145 | return object : MutableIterator> by iterator {
146 | private var lastKey: String? = null
147 |
148 | override fun remove() =
149 | iterator.remove().also {
150 | kv.remove(lastKey?.addPrefix())
151 | kv.encode(keysName, keys - lastKey)
152 | }
153 |
154 | override fun next(): MutableMap.MutableEntry {
155 | val entry = iterator.next()
156 | lastKey = entry.key
157 | return object : MutableMap.MutableEntry by entry {
158 | override fun setValue(newValue: V): V =
159 | entry.setValue(newValue).also { encode(key.addPrefix() to newValue) }
160 | }
161 | }
162 | }
163 | }
164 | }
165 | }
166 |
167 | override fun toString() = map.toString()
168 |
169 | override fun hashCode() = map.hashCode()
170 |
171 | override fun equals(other: Any?) = map == other
172 | }
--------------------------------------------------------------------------------
/README_ZH.md:
--------------------------------------------------------------------------------
1 | # MMKV-KTX
2 |
3 | [English](README.md) | 中文
4 |
5 | [](https://www.jitpack.io/#DylanCaiCoding/MMKV-KTX)
6 | [](https://github.com/DylanCaiCoding/MMKV-KTX/blob/master/LICENSE)
7 |
8 | 结合了 Kotlin 属性委托的特性,使得 [MMKV](https://github.com/Tencent/MMKV) 更加灵活易用。
9 |
10 | ## Features
11 |
12 | - 自动初始化 MMKV ;
13 | - 用属性名作为键名,无需声明大量的键名常量;
14 | - 可以确保类型安全,避免类型或者键名不一致导致的异常;
15 | - 支持转换成 `LiveData` 和 `StateFlow` 来使用;
16 | - 支持转换成 `Map`,可以根据不同的 `id` 来保存数据;
17 | - 支持 `getAllKV()`,为数据迁移提供了可能性;
18 |
19 | ## 用法
20 |
21 | :pencil: **[>> 使用文档 <<](https://dylancaicoding.github.io/MMKV-KTX)**
22 |
23 | ## 快速入门
24 |
25 |
26 | 在 `settings.gradle` 文件的 `repositories` 结尾处添加:
27 |
28 | ```groovy
29 | dependencyResolutionManagement {
30 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
31 | repositories {
32 | mavenCentral()
33 | maven { url 'https://www.jitpack.io' }
34 | }
35 | }
36 | ```
37 |
38 | 或者在 `settings.gradle.ktx` 文件的 `repositories` 结尾处添加:
39 |
40 | ```kotlin
41 | dependencyResolutionManagement {
42 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
43 | repositories {
44 | mavenCentral()
45 | maven { url = uri("https://jitpack.io") }
46 | }
47 | }
48 | ```
49 |
50 | 添加依赖:
51 |
52 | ```kotlin
53 | dependencies {
54 | implementation("com.github.DylanCaiCoding:MMKV-KTX:2.0.1")
55 | }
56 | ```
57 |
58 | 让一个类继承 `MMKVOwner` 类,即可在该类使用 `by mmkvXXXX()` 函数将属性委托给 `MMKV`,例如:
59 |
60 | ```kotlin
61 | object SettingsRepository : MMKVOwner(mmapID = "settings") {
62 | var isNightMode by mmkvBool()
63 | var language by mmkvString(default = "zh")
64 | }
65 | ```
66 |
67 | 如果已经有了父类继承不了,那就实现 `IMMKVOwner by MMKVOwner(mmapID)`,比如:
68 |
69 | ```kotlin
70 | object SettingsRepository : BaseRepository(), IMMKVOwner by MMKVOwner(mmapID = "settings") {
71 | // ...
72 | }
73 | ```
74 |
75 | **要确保每个 `mmapID` 不重复,只有这样才能 100% 确保类型安全!!!**
76 |
77 | 设置或获取属性的值会调用对应的 encode() 或 decode() 函数,用属性名作为键名。
78 |
79 | 支持以下类型:
80 |
81 | | 类型 | 函数 | 默认值 |
82 | | ------------ | ------------------ | ------------- |
83 | | `Int` | `mmkvInt()` | 0 |
84 | | `Long` | `mmkvLong()` | 0L |
85 | | `Boolean` | `mmkvBool()` | false |
86 | | `Float` | `mmkvFloat()` | 0f |
87 | | `Double` | `mmkvDouble()` | 0.0 |
88 | | `String` | `mmkvString()` | / |
89 | | `Set`| `mmkvStringSet()` | / |
90 | | `ByteArray` | `mmkvBytes()` | / |
91 | | `Parcelable` | `mmkvParcelable()` | / |
92 |
93 | | 类型 | 函数 | 默认值 |
94 | | ----------------------------- | ------------------------------- | ------------- |
95 | | `MutableLiveData` | `mmkvInt().asLiveData()` | 0 |
96 | | `MutableLiveData` | `mmkvLong().asLiveData()` | 0L |
97 | | `MutableLiveData` | `mmkvBool().asLiveData()` | false |
98 | | `MutableLiveData` | `mmkvFloat().asLiveData()` | 0f |
99 | | `MutableLiveData` | `mmkvDouble.asLiveData()` | 0.0 |
100 | | `MutableLiveData` | `mmkvString().asLiveData()` | / |
101 | | `MutableLiveData>`| `mmkvStringSet().asLiveData()` | / |
102 | | `MutableLiveData` | `mmkvBytes().asLiveData()` | / |
103 | | `MutableLiveData` | `mmkvParcelable().asLiveData()` | / |
104 |
105 | | 类型 | 函数 | 默认值 |
106 | | ------------------------------ | -------------------------------- | ------------- |
107 | | `MutableStateFlow` | `mmkvInt().asStateFlow()` | 0 |
108 | | `MutableStateFlow` | `mmkvLong().asStateFlow()` | 0L |
109 | | `MutableStateFlow` | `mmkvBool().asStateFlow()` | false |
110 | | `MutableStateFlow` | `mmkvFloat().asStateFlow()` | 0f |
111 | | `MutableStateFlow` | `mmkvDouble().asStateFlow()` | 0.0 |
112 | | `MutableStateFlow` | `mmkvString().asStateFlow()` | / |
113 | | `MutableStateFlow>`| `mmkvStringSet().asStateFlow()` | / |
114 | | `MutableStateFlow` | `mmkvBytes().asStateFlow()` | / |
115 | | `MutableStateFlow` | `mmkvParcelable().asStateFlow()` | / |
116 |
117 | | 类型 | 函数 | 默认值 |
118 | | -------------------------------- | -------------------------- | ------------- |
119 | | `MutableMap` | `mmkvInt().asMap()` | 0 |
120 | | `MutableMap` | `mmkvLong().asMap()` | 0L |
121 | | `MutableMap` | `mmkvBool().asMap()` | false |
122 | | `MutableMap` | `mmkvFloat().asMap()` | 0f |
123 | | `MutableMap` | `mmkvDouble().asMap()` | 0.0 |
124 | | `MutableMap` | `mmkvString().asMap()` | / |
125 | | `MutableMap>`| `mmkvStringSet().asMap()` | / |
126 | | `MutableMap` | `mmkvBytes().asMap()` | / |
127 | | `MutableMap` | `mmkvParcelable().asMap()` | / |
128 |
129 | 更多进阶用法请查看[使用文档](https://dylancaicoding.github.io/MMKV-KTX)。
130 |
131 | ## 更新日志
132 |
133 | [Releases](https://github.com/DylanCaiCoding/MMKV-KTX/releases)
134 |
135 | ## 作者其它的库
136 |
137 | | 库 | 简介 |
138 | | ------------------------------------------------------------ | ---------------------------------------------- |
139 | | [Longan](https://github.com/DylanCaiCoding/Longan) | 可能是最好用的 Kotlin 工具库 |
140 | | [LoadingStateView](https://github.com/DylanCaiCoding/LoadingStateView) | 深度解耦标题栏或加载中、加载失败、无数据等缺省页 |
141 | | [ViewBindingKTX](https://github.com/DylanCaiCoding/ViewBindingKTX) | 最全面的 ViewBinding 工具 |
142 | | [MultiBaseUrls](https://github.com/DylanCaiCoding/MultiBaseUrls) | 用注解让 Retrofit 同时支持多个 baseUrl 以及动态改变 baseUrl |
143 | | [Tracker](https://github.com/DylanCaiCoding/Tracker) | 基于西瓜视频的责任链埋点思路实现的轻量级埋点框架 |
144 |
145 | ## License
146 |
147 | ```
148 | Copyright (C) 2021. Dylan Cai
149 |
150 | Licensed under the Apache License, Version 2.0 (the "License");
151 | you may not use this file except in compliance with the License.
152 | You may obtain a copy of the License at
153 |
154 | http://www.apache.org/licenses/LICENSE-2.0
155 |
156 | Unless required by applicable law or agreed to in writing, software
157 | distributed under the License is distributed on an "AS IS" BASIS,
158 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
159 | See the License for the specific language governing permissions and
160 | limitations under the License.
161 | ```
162 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MMKV-KTX
2 |
3 | English | [中文](README_ZH.md)
4 |
5 | [](https://www.jitpack.io/#DylanCaiCoding/MMKV-KTX)
6 | [](https://github.com/DylanCaiCoding/MMKV-KTX/blob/master/LICENSE)
7 |
8 | Combined with the features of Kotlin property delegation makes [MMKV](https://github.com/Tencent/MMKV) more flexible and easy to use.
9 |
10 | ## Features
11 |
12 | - Automatically initializes MMKV;
13 | - Uses property names as keys, eliminating the need to declare numerous key constants;
14 | - Ensures type safety, avoiding exceptions caused by type or key mismatches;
15 | - Supports conversion to `LiveData` and `StateFlow` for usage;
16 | - Supports conversion to Map, allowing data to be saved based on different ids;
17 | - Supports `getAllKV()`, providing the possibility for data migration.
18 |
19 | ## Usage
20 |
21 | :pencil: **[>> Usage Document <<](https://dylancaicoding.github.io/MMKV-KTX)**
22 |
23 | ## Get started
24 |
25 | Add the following to the end of the repositories section in `settings.gradle`:
26 |
27 | ```groovy
28 | dependencyResolutionManagement {
29 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
30 | repositories {
31 | mavenCentral()
32 | maven { url 'https://www.jitpack.io' }
33 | }
34 | }
35 | ```
36 |
37 | Or add the following to the end of the repositories section in `settings.gradle.ktx`:
38 |
39 | ```kotlin
40 | dependencyResolutionManagement {
41 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
42 | repositories {
43 | mavenCentral()
44 | maven { url = uri("https://jitpack.io") }
45 | }
46 | }
47 | ```
48 |
49 | Add the dependency:
50 |
51 | ```kotlin
52 | dependencies {
53 | implementation("com.github.DylanCaiCoding:MMKV-KTX:2.0.1")
54 | }
55 | ```
56 |
57 | By having a class inherit from the `MMKVOwner` class, you can use the `by mmkvXXXX()` function to delegate properties to `MMKV`. For example:
58 |
59 | ```kotlin
60 | object SettingsRepository : MMKVOwner(mmapID = "settings") {
61 | var isNightMode by mmkvBool()
62 | var language by mmkvString(default = "zh")
63 | }
64 | ```
65 |
66 | If there is already a parent class that cannot be inherited, implement `IMMKVOwner by MMKVOwner(mmapID)`, like this:
67 |
68 | ```kotlin
69 | object SettingsRepository : BaseRepository(), IMMKVOwner by MMKVOwner(mmapID = "settings") {
70 | // ...
71 | }
72 | ```
73 |
74 | **Make sure that each mmapID is unique to 100% ensure type safety!!!**
75 |
76 | Setting or getting the property values will call the corresponding `encode()` or `decode()` functions, with the property name used as the key.
77 |
78 | Support the following types:
79 |
80 | | Type | Function | Default value |
81 | | ------------ | ------------------ | ------------- |
82 | | `Int` | `mmkvInt()` | 0 |
83 | | `Long` | `mmkvLong()` | 0L |
84 | | `Boolean` | `mmkvBool()` | false |
85 | | `Float` | `mmkvFloat()` | 0f |
86 | | `Double` | `mmkvDouble()` | 0.0 |
87 | | `String` | `mmkvString()` | / |
88 | | `Set`| `mmkvStringSet()` | / |
89 | | `ByteArray` | `mmkvBytes()` | / |
90 | | `Parcelable` | `mmkvParcelable()` | / |
91 |
92 | | Type | Function | Default value |
93 | | ----------------------------- | ------------------------------- | ------------- |
94 | | `MutableLiveData` | `mmkvInt().asLiveData()` | 0 |
95 | | `MutableLiveData` | `mmkvLong().asLiveData()` | 0L |
96 | | `MutableLiveData` | `mmkvBool().asLiveData()` | false |
97 | | `MutableLiveData` | `mmkvFloat().asLiveData()` | 0f |
98 | | `MutableLiveData` | `mmkvDouble.asLiveData()` | 0.0 |
99 | | `MutableLiveData` | `mmkvString().asLiveData()` | / |
100 | | `MutableLiveData>`| `mmkvStringSet().asLiveData()` | / |
101 | | `MutableLiveData` | `mmkvBytes().asLiveData()` | / |
102 | | `MutableLiveData` | `mmkvParcelable().asLiveData()` | / |
103 |
104 | | Type | Function | Default value |
105 | | ------------------------------ | -------------------------------- | ------------- |
106 | | `MutableStateFlow` | `mmkvInt().asStateFlow()` | 0 |
107 | | `MutableStateFlow` | `mmkvLong().asStateFlow()` | 0L |
108 | | `MutableStateFlow` | `mmkvBool().asStateFlow()` | false |
109 | | `MutableStateFlow` | `mmkvFloat().asStateFlow()` | 0f |
110 | | `MutableStateFlow` | `mmkvDouble().asStateFlow()` | 0.0 |
111 | | `MutableStateFlow` | `mmkvString().asStateFlow()` | / |
112 | | `MutableStateFlow>`| `mmkvStringSet().asStateFlow()` | / |
113 | | `MutableStateFlow` | `mmkvBytes().asStateFlow()` | / |
114 | | `MutableStateFlow` | `mmkvParcelable().asStateFlow()` | / |
115 |
116 | | Type | Function | Default value |
117 | | -------------------------------- | -------------------------- | ------------- |
118 | | `MutableMap` | `mmkvInt().asMap()` | 0 |
119 | | `MutableMap` | `mmkvLong().asMap()` | 0L |
120 | | `MutableMap` | `mmkvBool().asMap()` | false |
121 | | `MutableMap` | `mmkvFloat().asMap()` | 0f |
122 | | `MutableMap` | `mmkvDouble().asMap()` | 0.0 |
123 | | `MutableMap` | `mmkvString().asMap()` | / |
124 | | `MutableMap>`| `mmkvStringSet().asMap()` | / |
125 | | `MutableMap` | `mmkvBytes().asMap()` | / |
126 | | `MutableMap` | `mmkvParcelable().asMap()` | / |
127 |
128 | For more advanced usage, please refer to the [Usage Document](https://dylancaicoding.github.io/MMKV-KTX).
129 |
130 | ## Update log
131 |
132 | [Releases](https://github.com/DylanCaiCoding/MMKV-KTX/releases)
133 |
134 | ## Other libraries created by the author
135 |
136 | | Library | Brief Introduction |
137 | | ------------------------------------------------------------ | ------------------------------------------------------------ |
138 | | [Longan](https://github.com/DylanCaiCoding/Longan) | Perhaps the most user-friendly Kotlin tool library |
139 | | [LoadingStateView](https://github.com/DylanCaiCoding/LoadingStateView) | Deep decoupling of the default page of the title bar or loading, loading failure, no data, etc. |
140 | | [ViewBindingKTX](https://github.com/DylanCaiCoding/ViewBindingKTX) | Most comprehensive ViewBinding tool |
141 | | [MultiBaseUrls](https://github.com/DylanCaiCoding/MultiBaseUrls) | Use annotation to allow Retrofit to support multiple baseUrl and dynamically change baseUrl |
142 | | [Tracker](https://github.com/DylanCaiCoding/Tracker) | Lightweight burrowing framework based on the chain of responsibility burrowing idea of Buzzvideo |
143 |
144 | ## License
145 |
146 | ```
147 | Copyright (C) 2021. Dylan Cai
148 |
149 | Licensed under the Apache License, Version 2.0 (the "License");
150 | you may not use this file except in compliance with the License.
151 | You may obtain a copy of the License at
152 |
153 | http://www.apache.org/licenses/LICENSE-2.0
154 |
155 | Unless required by applicable law or agreed to in writing, software
156 | distributed under the License is distributed on an "AS IS" BASIS,
157 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
158 | See the License for the specific language governing permissions and
159 | limitations under the License.
160 | ```
161 |
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 |
2 | [](https://www.jitpack.io/#DylanCaiCoding/MMKV-KTX)
3 | [](https://github.com/DylanCaiCoding/LoadingStateView/blob/master/LICENSE)
4 | [](https://github.com/DylanCaiCoding/MMKV-KTX)
5 |
6 | 结合了 Kotlin 属性委托的特性,使得 [MMKV](https://github.com/Tencent/MMKV) 更加易用,无需初始化 MMKV,无需传 key 值。
7 |
8 | ## Features
9 |
10 | - 自动初始化 MMKV ;
11 | - 用属性名作为键名,无需声明大量的键名常量;
12 | - 可以确保类型安全,避免类型或者键名不一致导致的异常;
13 | - 支持转换成 `LiveData` 和 `StateFlow` 来使用;
14 | - 支持转换成 `Map`,可以根据不同的 `id` 来保存数据;
15 | - 支持 `getAllKV()`,为数据迁移提供了可能性;
16 |
17 | ## 快速入门
18 |
19 |
20 | 在 `settings.gradle` 文件的 `repositories` 结尾处添加:
21 |
22 | ```groovy
23 | dependencyResolutionManagement {
24 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
25 | repositories {
26 | mavenCentral()
27 | maven { url 'https://www.jitpack.io' }
28 | }
29 | }
30 | ```
31 |
32 | 或者在 `settings.gradle.ktx` 文件的 `repositories` 结尾处添加:
33 |
34 | ```kotlin
35 | dependencyResolutionManagement {
36 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
37 | repositories {
38 | mavenCentral()
39 | maven { url = uri("https://jitpack.io") }
40 | }
41 | }
42 | ```
43 |
44 | 添加依赖:
45 |
46 | ```kotlin
47 | dependencies {
48 | implementation("com.github.DylanCaiCoding:MMKV-KTX:2.0.1")
49 | }
50 | ```
51 |
52 | 让一个类继承 `MMKVOwner` 类,即可在该类使用 `by mmkvXXXX()` 函数将属性委托给 `MMKV`,例如:
53 |
54 | ```kotlin
55 | object SettingsRepository : MMKVOwner(mmapID = "settings") {
56 | var isNightMode by mmkvBool()
57 | var language by mmkvString(default = "zh")
58 | }
59 | ```
60 |
61 | 如果已经有了父类继承不了,那就实现 `IMMKVOwner by MMKVOwner(mmapID)`,比如:
62 |
63 | ```kotlin
64 | object SettingsRepository : BaseRepository(), IMMKVOwner by MMKVOwner(mmapID = "settings") {
65 | // ...
66 | }
67 | ```
68 |
69 | **要确保每个 `mmapID` 不重复,只有这样才能 100% 确保类型安全!!!**
70 |
71 | 设置或获取属性的值会调用对应的 encode() 或 decode() 函数,用属性名作为键名。
72 |
73 | 支持以下类型:
74 |
75 | | 类型 | 函数 | 默认值 |
76 | | ------------ | ------------------ | ------------- |
77 | | `Int` | `mmkvInt()` | 0 |
78 | | `Long` | `mmkvLong()` | 0L |
79 | | `Boolean` | `mmkvBool()` | false |
80 | | `Float` | `mmkvFloat()` | 0f |
81 | | `Double` | `mmkvDouble()` | 0.0 |
82 | | `String` | `mmkvString()` | / |
83 | | `Set`| `mmkvStringSet()` | / |
84 | | `ByteArray` | `mmkvBytes()` | / |
85 | | `Parcelable` | `mmkvParcelable()` | / |
86 |
87 | | 类型 | 函数 | 默认值 |
88 | | ----------------------------- | ------------------------------- | ------------- |
89 | | `MutableLiveData` | `mmkvInt().asLiveData()` | 0 |
90 | | `MutableLiveData` | `mmkvLong().asLiveData()` | 0L |
91 | | `MutableLiveData` | `mmkvBool().asLiveData()` | false |
92 | | `MutableLiveData` | `mmkvFloat().asLiveData()` | 0f |
93 | | `MutableLiveData` | `mmkvDouble.asLiveData()` | 0.0 |
94 | | `MutableLiveData` | `mmkvString().asLiveData()` | / |
95 | | `MutableLiveData>`| `mmkvStringSet().asLiveData()` | / |
96 | | `MutableLiveData` | `mmkvBytes().asLiveData()` | / |
97 | | `MutableLiveData` | `mmkvParcelable().asLiveData()` | / |
98 |
99 | | 类型 | 函数 | 默认值 |
100 | | ------------------------------ | -------------------------------- | ------------- |
101 | | `MutableStateFlow` | `mmkvInt().asStateFlow()` | 0 |
102 | | `MutableStateFlow` | `mmkvLong().asStateFlow()` | 0L |
103 | | `MutableStateFlow` | `mmkvBool().asStateFlow()` | false |
104 | | `MutableStateFlow` | `mmkvFloat().asStateFlow()` | 0f |
105 | | `MutableStateFlow` | `mmkvDouble().asStateFlow()` | 0.0 |
106 | | `MutableStateFlow` | `mmkvString().asStateFlow()` | / |
107 | | `MutableStateFlow>`| `mmkvStringSet().asStateFlow()` | / |
108 | | `MutableStateFlow` | `mmkvBytes().asStateFlow()` | / |
109 | | `MutableStateFlow` | `mmkvParcelable().asStateFlow()` | / |
110 |
111 | | 类型 | 函数 | 默认值 |
112 | | -------------------------------- | -------------------------- | ------------- |
113 | | `MutableMap` | `mmkvInt().asMap()` | 0 |
114 | | `MutableMap` | `mmkvLong().asMap()` | 0L |
115 | | `MutableMap` | `mmkvBool().asMap()` | false |
116 | | `MutableMap` | `mmkvFloat().asMap()` | 0f |
117 | | `MutableMap` | `mmkvDouble().asMap()` | 0.0 |
118 | | `MutableMap` | `mmkvString().asMap()` | / |
119 | | `MutableMap>`| `mmkvStringSet().asMap()` | / |
120 | | `MutableMap` | `mmkvBytes().asMap()` | / |
121 | | `MutableMap` | `mmkvParcelable().asMap()` | / |
122 |
123 | 可以用 `clearAllKV()` 清理缓存。
124 |
125 | ## 进阶用法
126 |
127 | ### 修改 MMKV 初始化配置
128 |
129 | 可以使用 `` 来修改存储位置或者 log 等级。
130 |
131 | ```xml
132 |
135 |
136 |
139 | ```
140 |
141 | ### 重写 kv 对象
142 |
143 | 有一些场景需要使用新的 MMKV 对象,此时可以重写 `kv` 属性。
144 |
145 | #### 多进程
146 |
147 | MMKV 默认是单进程模式,如果你需要多进程支持:
148 |
149 | ```kotlin
150 | object SettingsRepository : MMKVOwner(mmapID = "settings") {
151 | // ...
152 |
153 | override val kv: MMKV = MMKV.mmkvWithID(mmapID, MMKV.MULTI_PROCESS_MODE)
154 | }
155 | ```
156 |
157 | 或者:
158 |
159 | ```kotlin
160 | object SettingsRepository : BaseRepository(), IMMKVOwner by MMKVOwner(mmapID = "settings") {
161 | // ...
162 |
163 | override val kv: MMKV = MMKV.mmkvWithID(mmapID, MMKV.MULTI_PROCESS_MODE)
164 | }
165 | ```
166 |
167 | #### 加密
168 |
169 | MMKV 默认明文存储所有 key-value,依赖 Android 系统的沙盒机制保证文件加密。如果你担心信息泄露,你可以选择加密 MMKV。
170 |
171 | ```kotlin
172 | object SettingsRepository : MMKVOwner(mmapID = "settings") {
173 | // ...
174 |
175 | private const val CRYPT_KEY = "My-Encrypt-Key"
176 |
177 | override val kv: MMKV = MMKV.mmkvWithID(mmapID, MMKV.SINGLE_PROCESS_MODE, CRYPT_KEY)
178 | }
179 | ```
180 |
181 | 或者:
182 |
183 | ```kotlin
184 | object SettingsRepository : BaseRepository(), IMMKVOwner by MMKVOwner(mmapID = "settings") {
185 | // ...
186 |
187 | private const val CRYPT_KEY = "My-Encrypt-Key"
188 |
189 | override val kv: MMKV = MMKV.mmkvWithID(mmapID, MMKV.SINGLE_PROCESS_MODE, CRYPT_KEY)
190 | }
191 | ```
192 |
193 | ## 更新日志
194 |
195 | [Releases](https://github.com/DylanCaiCoding/MMKV-KTX/releases)
196 |
197 | ## 作者其它的库
198 |
199 | | 库 | 简介 |
200 | | ------------------------------------------------------------ |------------------------------------------|
201 | | [Longan](https://github.com/DylanCaiCoding/Longan) | 可能是最好用的 Kotlin 工具库 |
202 | | [LoadingStateView](https://github.com/DylanCaiCoding/LoadingStateView) | 深度解耦标题栏或加载中、加载失败、无数据等视图,支持两行代码集成到基类 |
203 | | [ViewBindingKTX](https://github.com/DylanCaiCoding/ViewBindingKTX) | 最全面的 ViewBinding 工具,可用各种姿势使用 ViewBinding |
204 | | [Tracker](https://github.com/DylanCaiCoding/Tracker) | 基于西瓜视频的责任链埋点思路实现的轻量级埋点框架 |
205 |
206 | ## License
207 |
208 | ```
209 | Copyright (C) 2021. Dylan Cai
210 |
211 | Licensed under the Apache License, Version 2.0 (the "License");
212 | you may not use this file except in compliance with the License.
213 | You may obtain a copy of the License at
214 |
215 | http://www.apache.org/licenses/LICENSE-2.0
216 |
217 | Unless required by applicable law or agreed to in writing, software
218 | distributed under the License is distributed on an "AS IS" BASIS,
219 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
220 | See the License for the specific language governing permissions and
221 | limitations under the License.
222 | ```
223 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/com/dylanc/mmkv/MMKVTest.kt:
--------------------------------------------------------------------------------
1 | package com.dylanc.mmkv
2 |
3 | import android.os.Parcelable
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 | import androidx.test.internal.runner.junit4.statement.UiThreadStatement
6 | import com.tencent.mmkv.MMKV
7 | import kotlinx.parcelize.Parcelize
8 | import org.junit.Assert
9 | import org.junit.Before
10 | import org.junit.Test
11 | import org.junit.runner.RunWith
12 | import kotlin.properties.ReadWriteProperty
13 | import kotlin.reflect.KProperty
14 |
15 | /**
16 | * @author Dylan Cai
17 | */
18 | @RunWith(AndroidJUnit4::class)
19 | class MMKVTest : IMMKVOwner by MMKVOwner(mmapID = "test") {
20 |
21 | private var i1 by mmkvInt()
22 | private var i2 by mmkvInt(default = -1)
23 | private var l1 by mmkvLong()
24 | private var l2 by mmkvLong(default = -1L)
25 | private var b1 by mmkvBool()
26 | private var b2 by mmkvBool(default = true)
27 | private var f1 by mmkvFloat()
28 | private var f2 by mmkvFloat(default = -1f)
29 | private var d1 by mmkvDouble()
30 | private var d2 by mmkvDouble(default = -1.0)
31 | private var s1 by mmkvString()
32 | private var s2 by mmkvString(default = "")
33 | private var set1 by mmkvStringSet()
34 | private var set2 by mmkvStringSet(default = emptySet())
35 | private var bytes1 by mmkvBytes()
36 | private var bytes2 by mmkvBytes(default = byteArrayOf(0x1A))
37 | private var user1 by mmkvParcelable()
38 | private var user2 by mmkvParcelable(default = User(0, "Admin"))
39 | private val liveData1 by mmkvInt().asLiveData()
40 | private val liveData2 by mmkvInt(default = -1).asLiveData()
41 | private val flow1 by mmkvInt().asStateFlow()
42 | private val flow2 by mmkvInt(default = -1).asStateFlow()
43 | private val map1 by mmkvInt().asMap()
44 | private val map2 by mmkvInt(-1).asMap()
45 |
46 | override val kv: MMKV = MMKV.mmkvWithID(mmapID, MMKV.MULTI_PROCESS_MODE)
47 |
48 | // private val test by TestProperty()
49 |
50 | class TestProperty: ReadWriteProperty {
51 | override fun getValue(thisRef: Any, property: KProperty<*>): Int {
52 | return 1
53 | }
54 |
55 | override fun setValue(thisRef: Any, property: KProperty<*>, value: Int) {
56 | }
57 | }
58 |
59 | @Before
60 | fun clear() {
61 | kv.clearAll()
62 | }
63 |
64 | @Test
65 | fun putInt1() {
66 | Assert.assertEquals(0, i1)
67 | i1 = 6
68 | Assert.assertEquals(6, i1)
69 | }
70 |
71 | @Test
72 | fun putInt2() {
73 | Assert.assertEquals(-1, i2)
74 | i2 = 6
75 | Assert.assertEquals(6, i2)
76 | }
77 |
78 | @Test
79 | fun putLong1() {
80 | Assert.assertEquals(0L, l1)
81 | l1 = 3L
82 | Assert.assertEquals(3L, l1)
83 | }
84 |
85 | @Test
86 | fun putLong2() {
87 | Assert.assertEquals(-1L, l2)
88 | l2 = 3L
89 | Assert.assertEquals(3L, l2)
90 | }
91 |
92 | @Test
93 | fun putBoolean1() {
94 | Assert.assertEquals(false, b1)
95 | b1 = true
96 | Assert.assertEquals(true, b1)
97 | }
98 |
99 | @Test
100 | fun putBoolean2() {
101 | Assert.assertEquals(true, b2)
102 | b2 = true
103 | Assert.assertEquals(true, b2)
104 | }
105 |
106 | @Test
107 | fun putFloat1() {
108 | Assert.assertEquals(0f, f1)
109 | f1 = 0.5f
110 | Assert.assertEquals(0.5f, f1)
111 | }
112 |
113 | @Test
114 | fun putFloat2() {
115 | Assert.assertEquals(-1f, f2)
116 | f2 = 0.5f
117 | Assert.assertEquals(0.5f, f2)
118 | }
119 |
120 | @Test
121 | fun putDouble1() {
122 | Assert.assertEquals(0.0, d1, 0.0)
123 | d1 = 0.5
124 | Assert.assertEquals(0.5, d1, 0.0)
125 | }
126 |
127 | @Test
128 | fun putDouble2() {
129 | Assert.assertEquals(-1.0, d2, 0.0)
130 | d2 = 0.5
131 | Assert.assertEquals(0.5, d2, 0.0)
132 | }
133 |
134 | @Test
135 | fun putString1() {
136 | Assert.assertEquals(null, s1)
137 | s1 = "test"
138 | Assert.assertEquals("test", s1)
139 | }
140 |
141 | @Test
142 | fun putString2() {
143 | Assert.assertEquals("", s2)
144 | s2 = "test"
145 | Assert.assertEquals("test", s2)
146 | }
147 |
148 | @Test
149 | fun putSet1() {
150 | Assert.assertEquals(null, set1)
151 | val set = setOf("22", "33")
152 | set1 = set
153 | Assert.assertEquals(set, set1)
154 | }
155 |
156 | @Test
157 | fun putSet2() {
158 | Assert.assertEquals(emptySet(), set2)
159 | val set = setOf("22", "33")
160 | set2 = set
161 | Assert.assertEquals(set, set2)
162 | }
163 |
164 | @Test
165 | fun putBytes1() {
166 | Assert.assertEquals(null, bytes1)
167 | val bytes = byteArrayOf(0x1A, 0x2B)
168 | bytes1 = bytes
169 | Assert.assertTrue(bytes.contentEquals(bytes1))
170 | }
171 |
172 | @Test
173 | fun putBytes2() {
174 | Assert.assertTrue(byteArrayOf(0x1A).contentEquals(bytes2))
175 | val bytes = byteArrayOf(0x1A, 0x2B)
176 | bytes2 = bytes
177 | Assert.assertTrue(bytes.contentEquals(bytes2))
178 | }
179 |
180 | @Test
181 | fun putParcelable1() {
182 | Assert.assertEquals(null, user1)
183 | user1 = User(1, "DylanCai")
184 | Assert.assertEquals(User(1, "DylanCai"), user1)
185 | }
186 |
187 | @Test
188 | fun putParcelable2() {
189 | Assert.assertEquals(User(0, "Admin"), user2)
190 | user2 = User(1, "DylanCai")
191 | Assert.assertEquals(User(1, "DylanCai"), user2)
192 | }
193 |
194 | @Test
195 | fun putLiveData1() {
196 | UiThreadStatement.runOnUiThread {
197 | Assert.assertEquals(0, liveData1.value)
198 | liveData1.value = 6
199 | Assert.assertEquals(6, liveData1.value)
200 | clearAllKV()
201 | Assert.assertEquals(0, liveData1.value)
202 | }
203 | }
204 |
205 | @Test
206 | fun putLiveData2() {
207 | UiThreadStatement.runOnUiThread {
208 | Assert.assertEquals(-1, liveData2.value)
209 | liveData2.value = 6
210 | Assert.assertEquals(6, liveData2.value)
211 | clearAllKV()
212 | Assert.assertEquals(-1, liveData2.value)
213 | }
214 | }
215 |
216 | @Test
217 | fun putFlow1() {
218 | Assert.assertEquals(0, flow1.value)
219 | flow1.value = 6
220 | Assert.assertEquals(6, flow1.value)
221 | clearAllKV()
222 | Assert.assertEquals(0, flow1.value)
223 | }
224 |
225 | @Test
226 | fun putFlow2() {
227 | Assert.assertEquals(-1, flow2.value)
228 | flow2.value = 6
229 | Assert.assertEquals(6, flow2.value)
230 | clearAllKV()
231 | Assert.assertEquals(-1, flow2.value)
232 | }
233 |
234 | @Test
235 | fun putMapData1() {
236 | Assert.assertEquals(0, map1["id1"])
237 | Assert.assertEquals(0, map1["id2"])
238 | map1["id1"] = 1
239 | map1["id2"] = 2
240 | Assert.assertEquals(1, map1["id1"])
241 | Assert.assertEquals(2, map1["id2"])
242 | map1.clear()
243 | Assert.assertEquals(0, map1["id1"])
244 | Assert.assertEquals(0, map1["id2"])
245 | map1["id1"] = 3
246 | map1["id2"] = 4
247 | clearAllKV()
248 | Assert.assertEquals(0, map1["id1"])
249 | Assert.assertEquals(0, map1["id2"])
250 | }
251 |
252 | @Test
253 | fun putMapData2() {
254 | Assert.assertEquals(-1, map2["id1"])
255 | Assert.assertEquals(-1, map2["id2"])
256 | map2["id1"] = 1
257 | map2["id2"] = 2
258 | Assert.assertEquals(1, map2["id1"])
259 | Assert.assertEquals(2, map2["id2"])
260 | map2.clear()
261 | Assert.assertEquals(-1, map2["id1"])
262 | Assert.assertEquals(-1, map2["id2"])
263 | map2["id1"] = 3
264 | map2["id2"] = 4
265 | Assert.assertEquals(3, map2["id1"])
266 | Assert.assertEquals(4, map2["id2"])
267 | clearAllKV()
268 | Assert.assertEquals(-1, map2["id1"])
269 | Assert.assertEquals(-1, map2["id2"])
270 | Assert.assertEquals(0, map2.size)
271 | }
272 |
273 | @Test
274 | fun removeValueForKey() {
275 | map1["id1"] = 1
276 | map1["id2"] = 2
277 | Assert.assertEquals(1, map1["id1"])
278 | Assert.assertEquals(2, map1["id2"])
279 | val iterator = map1.entries.iterator()
280 | while (iterator.hasNext()) {
281 | val entry = iterator.next()
282 | if (entry.key == "id1") {
283 | iterator.remove()
284 | }
285 | }
286 | Assert.assertEquals(0, map1["id1"])
287 | Assert.assertEquals(2, map1["id2"])
288 | Assert.assertEquals(1, map1.size)
289 |
290 | map1.entries.removeIf { it.key == "id2" }
291 | Assert.assertEquals(0, map1["id2"])
292 | Assert.assertEquals(0, map1.size)
293 |
294 | map1["merge"] = 1
295 | map1.merge("merge", 2) { oldValue, newValue -> oldValue + newValue }
296 | Assert.assertEquals(3, map1["merge"])
297 | }
298 |
299 | @Test
300 | fun removeValue() {
301 | i1 = 6
302 | Assert.assertTrue(kv.containsKey(::i1.name))
303 | kv.removeValueForKey(::i1.name)
304 | Assert.assertFalse(kv.containsKey(::i1.name))
305 | }
306 |
307 | @Test
308 | fun removeValues() {
309 | s1 = "1"
310 | s2 = "2"
311 | Assert.assertTrue(kv.containsKey(::s1.name))
312 | Assert.assertTrue(kv.containsKey(::s2.name))
313 | kv.removeValuesForKeys(arrayOf(::s1.name, ::s2.name))
314 | Assert.assertFalse(kv.containsKey(::s1.name))
315 | Assert.assertFalse(kv.containsKey(::s2.name))
316 | }
317 |
318 | @Test
319 | fun getAll() {
320 | clearAllKV()
321 | map1["id1"] = 1
322 | map1["id2"] = 2
323 | Assert.assertEquals(setOf("id1", "id2"), map1.keys)
324 | val allKV = getAllKV()
325 | Assert.assertEquals(24, allKV.size)
326 | Assert.assertEquals(0, allKV["i1"])
327 | Assert.assertEquals(-1, allKV["i2"])
328 | Assert.assertEquals(0L, allKV["l1"])
329 | Assert.assertEquals(-1L, allKV["l2"])
330 | Assert.assertEquals(false, allKV["b1"])
331 | Assert.assertEquals(true, allKV["b2"])
332 | Assert.assertEquals(0f, allKV["f1"])
333 | Assert.assertEquals(-1f, allKV["f2"])
334 | Assert.assertEquals(0.0, allKV["d1"])
335 | Assert.assertEquals(-1.0, allKV["d2"])
336 | Assert.assertEquals(null, allKV["s1"])
337 | Assert.assertEquals("", allKV["s2"])
338 | Assert.assertEquals(null, allKV["set1"])
339 | Assert.assertEquals(emptySet(), allKV["set2"])
340 | Assert.assertEquals(null, allKV["bytes1"])
341 | Assert.assertTrue(byteArrayOf(0x1A).contentEquals(allKV["bytes2"] as? ByteArray))
342 | Assert.assertEquals(null, allKV["user1"])
343 | Assert.assertEquals(User(0, "Admin"), allKV["user2"])
344 | Assert.assertEquals(0, allKV["liveData1"])
345 | Assert.assertEquals(-1, allKV["liveData2"])
346 | Assert.assertEquals(0, allKV["flow1"])
347 | Assert.assertEquals(-1, allKV["flow2"])
348 | Assert.assertEquals(mapOf("id1" to 1, "id2" to 2), allKV["map1"])
349 | Assert.assertEquals(emptyMap(), allKV["map2"])
350 | }
351 |
352 | @Parcelize
353 | data class User(val id: Long, val name: String) : Parcelable
354 | }
355 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------