Code Monkey home page Code Monkey logo

mmkv-ktx's Introduction

MMKV-KTX

English | 中文

License

Combined with the features of Kotlin property delegation, it makes MMKV more flexible and easy to use.

Features

  • Automatic initialization of MMKV;
  • Use the property name as the key name, eliminating the need to declare a large number of key name constants;
  • Can ensure type safety and avoid exceptions caused by inconsistent types or key values;

Usage

📝 >> Usage Document <<

Get started

Add the following to the build.gradle file in the root directory:

allprojects {
    repositories {
        //...
        maven { url 'https://www.jitpack.io' }
    }
}

Add the dependency in the module's build.gradle file:

dependencies {
    implementation 'com.github.DylanCaiCoding:MMKV-KTX:1.2.16'
}

By having a class inherit from the MMKVOwner class, you can use the by mmkvXXXX() function to delegate properties to MMKV. For example:

object SettingsRepository : MMKVOwner(mmapID = "settings") {
  var isNightMode by mmkvBool()
  var language by mmkvString(default = "zh")
}

If you already have a parent class that cannot be inherited from, implement IMMKVOwner by MMKVOwner(mmapID), such as:

object SettingsRepository : BaseRepository(), IMMKVOwner by MMKVOwner(mmapID = "settings") {
  // ...
}

Make sure that each mmapID is unique to ensure type safety 100%!!!

Setting or getting the value of a property will call the corresponding encode() or decode() function with the property name as the key name. For example:

if (SettingsRepository.isNightMode) {
  // do some thing
}

SettingsRepository.isNightMode = true

Support the following types:

Function Default value
mmkvInt() 0
mmkvLong() 0L
mmkvBool() false
mmkvFloat() 0f
mmkvDouble() 0.0
mmkvString() /
mmkvStringSet() /
mmkvBytes() /
mmkvParcelable() /

Support using the mmkvXXXX().asLiveData() function to delegate the property to LiveData, such as:

object SettingRepository : MMKVOwner(mmapID = "settings") {
  val isNightMode by mmkvBool().asLiveData()
}

SettingRepository.isNightMode.observe(this) {
  checkBox.isChecked = it
}

SettingRepository.isNightMode.value = true

The kv object can be used to delete values or clear the cache, for example:

kv.removeValueForKey(::language.name) // Recommend removing the key after the default value is modified to shorten the assignment operation
kv.clearAll()

For more advanced usage, please refer to the Usage Document.

Update log

Releases

Other libraries created by the author

Library Brief Introduction
Longan Perhaps the most user-friendly Kotlin tool library
LoadingStateView Deep decoupling of the default page of the title bar or loading, loading failure, no data, etc.
ViewBindingKTX Most comprehensive ViewBinding tool
Tracker Lightweight burrowing framework based on the chain of responsibility burrowing idea of Buzzvideo

License

Copyright (C) 2021. Dylan Cai

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

mmkv-ktx's People

Contributors

dylancaicoding avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

mmkv-ktx's Issues

java.lang.RuntimeException: Unable to get provider androidx.startup.InitializationProvider: androidx.startup.StartupException: java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.musicho.andro-jmxJoVRLaDJ_0L_kHWTQdA==/base.apk"],nativeLibraryDirectories=[/data/app/com.musicho.andro-jmxJoVRLaDJ_0L_kHWTQdA==/lib/x86, /system/lib, /vendor/lib]]] couldn't find "libmmkv.so"

在firebase上看到的崩溃,不知道怎么处理,麻烦大佬看下,我现在是在build.gradle下加了
ndk { //APP的build.gradle设置支持的SO库架构 abiFilters 'armeabi-v7a', "armeabi", "arm64-v8a", 'x86_64' }

完整崩溃日志
com.musicho.andro_issue_61117a57833c6664c9bdb1c17f8b13bf_crash_session_6619E09201CB00011A5473926F8486A4_DNE_0_v2_stacktrace.txt

提个bug

MMKVProperty中有private var cache: V? = null,并在set和get中对其赋值,这是个比较好的优化方案,但我如果使用了removeValueForKey的话,并不会去清空cache的值,会导致清空了也一直返回上次保存或者上次获取到的值。

再提个bug,多进程初始化的情况

如果是多进程初始化,使用Initializer进行mmkv的初始化,但是如果再application的oncreate进行调用,没有判断是否是主进程的情况下,非主进程MMKVOwner.default就会为null

能提供MMKV初始化配置吗?

我看初始化用的是startup延迟初始化?而且只有一个默认初始化,如果我想指定MMKV文件存储位置或其他配置的话,这个我要自己手动初始化?

请问如何单独存一个值呢

不知道我这样写对不对

object LanguageRepository : MMKVOwner {

override val kv: MMKV
    get() = MMKV.mmkvWithID("language")

val currLang by mmkvString()

fun putCurrLang(language: String) {
    kv.encode(::currLang.name, language)
}

fun clearCurrLang() {
    kv.removeValueForKey(::currLang.name)
}

}

Exception java.lang.ExceptionInInitializerError

Exception java.lang.ExceptionInInitializerError:
at com.dylanc.mmkv.MMKVKt.mmkvString
at com.nova.dax.common.storage.AppStorage. (AppStorage.kt:21)
at com.nova.dax.common.ext.ActivityExtKt.resetThemeBar (ActivityExt.kt:47)
at com.nova.dax.common.ext.ActivityExtKt.resetThemeBar$default (ActivityExt.kt:44)
at com.nova.dax.base.BaseActivity.onCreate (BaseActivity.kt:26)
at com.nova.dax.ui.main.MainActivity.onCreate (MainActivity.kt:47)
at android.app.Activity.performCreate (Activity.java:8207)
at android.app.Activity.performCreate (Activity.java:8191)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3819)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:4022)
at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2336)
at android.os.Handler.dispatchMessage (Handler.java:106)
at android.os.Looper.loop (Looper.java:246)
at android.app.ActivityThread.main (ActivityThread.java:8653)
at java.lang.reflect.Method.invoke
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1130)
Caused by java.lang.IllegalStateException: You should Call MMKV.initialize() first.
at com.tencent.mmkv.MMKV.defaultMMKV (MMKV.java:468)
at com.dylanc.mmkv.MMKVKt. (MMKV.kt:43)

AppStorage的第21行代码是:

var baseUrl by mmkvString(Const.BASE_URL) // 连接服务端的环境

目前上面的异常在samsung a01q;samsung a30;asus ASUS_A001D_1这三套机型上报了50多次,不明白是啥原因,其它手机都正常,自己也没有重现,不知大佬知道可能的原因不?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.