Skip to content

Commit

Permalink
升级最新依赖,很多 api 都变了
Browse files Browse the repository at this point in the history
  • Loading branch information
li-yu committed Mar 17, 2022
1 parent 2f55e9a commit d5c117d
Show file tree
Hide file tree
Showing 15 changed files with 170 additions and 122 deletions.
16 changes: 0 additions & 16 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions .idea/jarRepositories.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

82 changes: 45 additions & 37 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,68 +7,72 @@
这几天抽空学习了下基本用法,基于 Preferences DataStore 实现了一个简单的数据存储扩展,还是熟悉的样子,还是熟悉的配方,这就是全新 **DsPreferences**

## 添加依赖

1. 添加 jitpack 源到工程 build.gradle :
```
allprojects {

```
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
```
}
```

2. 添加 DsPreferences 依赖:
```
implementation 'com.github.li-yu:DataStoreExt:1.0.0'
```

```
implementation 'com.github.li-yu:DataStoreExt:1.1.0'
```

## 使用
目前支持基本数据类型:Int, Long, Boolean, Float, Double, String 以及自定义 Converter 实现复杂实体类型的存取。

#### 初始化!!!
务必一定初始化!!!如果只是基本数据类型的存取,用 `DsPreferences.init(this)` 初始化即可,当然也可选支持自定义文件名和 Converter。
``` kotlin
class App : Application() {
override fun onCreate() {
super.onCreate()
DsPreferences.init(this)
}
}
```
目前支持基本数据类型:Int, Long, Boolean, Float, Double, String 以及自定义 Converter 实现复杂实体类型的存取。

#### 1. 传统用法

与原先的 SharedPreferences 主流包装用法没有差异,只是要注意所有读写操作要放在协程里。
``` kotlin

```kotlin
// 实例化
val dsPreferences by lazy {
DsPreferences(this)
}

//
DsPreferences.set("name", "frank") // 字符串类型
DsPreferences.set("age", 18) // 数字类型
DsPreferences.set("foo", foo) // 自定义实体类型
dsPreferences.set("name", "frank") // 字符串类型
dsPreferences.set("age", 18) // 数字类型
dsPreferences.set("foo", foo) // 自定义实体类型

//
val foo = DsPreferences.get("name", "default")
val age = DsPreferences.get("age", -1)
val foo = DsPreferences.get<Foo>("foo") // 如果读取失败则返回 null
val foo = dsPreferences.get("name", "default")
val age = dsPreferences.get("age", -1)
val foo = dsPreferences.get<Foo>("foo") // 如果读取失败则返回 null
```

#### 2. ViewModel + LiveData 用法

官方推荐的用法,不过实际使用场景可能不一样,下面是一个简单的示例:
``` kotlin
class MainViewModel : ViewModel() {

```kotlin
class MainViewModel(dsPreferences: DsPreferences) : ViewModel() {

// Flow 通过扩展函数转为 LiveData
var appSettings = DsPreferences.flow("settings","DefaultValue").asLiveData()
var appSettings = dsPreferences.flow("settings","DefaultValue").asLiveData()
}

...
// 观察 LiveData
viewModel.appSettings.observe(this, { value ->
viewModel.appSettings.observe(this) { value ->
showValue(value)
})
```

#### 3. 自定义 Converter 实现复杂类型用法

和 SharedPreferences 一样,DataStore 同样不推荐存储复杂的大数据,但是聊胜于无。
``` kotlin

```kotlin
interface Converter {

// 系列化为字符串
Expand All @@ -78,8 +82,10 @@ interface Converter {
fun <T> deserialize(serialized: String, clazz: Class<T>): T?
}
```

下面是一个简单的 `GsonConverter` 实现供参考:
``` kotlin

```kotlin
class GsonConverter(val gson: Gson) : Converter {
override fun serialize(value: Any): String {
return gson.toJson(value)
Expand All @@ -90,17 +96,19 @@ class GsonConverter(val gson: Gson) : Converter {
}
}
```
最后记得在 DsPreferences 初始化时传入自定义的 Converter:
```
DsPreferences.init(this, converter = GsonConverter(Gson()))

最后记得在任意地方设置自定义的 Converter:

```kotlin
DsPreferences.converter = GsonConverter(Gson())
```

然后就可以使用了:

``` kotlin
DsPreferences.set("foo", foo)
```kotlin
dsPreferences.set("foo", foo)
...
val foo = DsPreferences.get<Foo>("foo")
val foo = dsPreferences.get<Foo>("foo")
```

## 未完成的功能
Expand Down
17 changes: 6 additions & 11 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ plugins {
}

android {
compileSdkVersion 30
buildToolsVersion "30.0.0"
compileSdkVersion 31

defaultConfig {
applicationId "cn.liyuyu.datastoreext"
minSdkVersion 23
targetSdkVersion 30
targetSdkVersion 31
versionCode 1
versionName "1.0"

Expand All @@ -34,14 +33,10 @@ android {

dependencies {

implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
implementation project(':lib')
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4'
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.DataStoreExt">
<activity android:name=".MainActivity">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/cn/liyuyu/datastoreext/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ import com.google.gson.Gson
class App : Application() {
override fun onCreate() {
super.onCreate()
DsPreferences.init(this, converter = GsonConverter(Gson()))
DsPreferences.converter = GsonConverter(Gson())
}
}
12 changes: 8 additions & 4 deletions app/src/main/java/cn/liyuyu/datastoreext/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ import kotlinx.coroutines.*
class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {

private val viewModel: MainViewModel by lazy {
ViewModelProvider(this).get(MainViewModel::class.java)
ViewModelProvider(this, ViewModelFactory(dsPreferences)).get(MainViewModel::class.java)
}

private val dsPreferences by lazy {
DsPreferences(this)
}

override fun onCreate(savedInstanceState: Bundle?) {
Expand All @@ -21,8 +25,8 @@ class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {

launch(Dispatchers.IO) {
var foo = Foo("bar", 18)
DsPreferences.set("foo", foo)
val value = DsPreferences.get<Foo>("foo")
dsPreferences.set("foo", foo)
val value = dsPreferences.get<Foo>("foo")
withContext(Dispatchers.Main) {
findViewById<TextView>(R.id.tvValue).text = value.toString()
}
Expand All @@ -37,7 +41,7 @@ class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {
val text = findViewById<EditText>(R.id.editText).text.toString()
if (text.isNotEmpty()) {
launch(Dispatchers.IO) {
DsPreferences.set("settings", text)
dsPreferences.set("settings", text)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/java/cn/liyuyu/datastoreext/MainViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import cn.liyuyu.datastoreext.core.DsPreferences

class MainViewModel : ViewModel() {
class MainViewModel(dsPreferences: DsPreferences) : ViewModel() {

var appSettings = DsPreferences.flow("settings","DefaultValue").asLiveData()
var appSettings = dsPreferences.flow("settings", "DefaultValue").asLiveData()
}
19 changes: 19 additions & 0 deletions app/src/main/java/cn/liyuyu/datastoreext/ViewModelFactory.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package cn.liyuyu.datastoreext

import android.R.attr.name
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import cn.liyuyu.datastoreext.core.DsPreferences


/**
* Created by frank on 2022/3/17.
*/
class ViewModelFactory(private val dsPreferences: DsPreferences) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
return MainViewModel(dsPreferences) as T
}
throw RuntimeException("unknown class :" + modelClass.name)
}
}
9 changes: 4 additions & 5 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.21"
ext.kotlin_version = "1.6.10"
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
classpath 'com.android.tools.build:gradle:7.1.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

Expand All @@ -19,6 +17,7 @@ allprojects {
google()
jcenter()
maven { url 'https://jitpack.io' }
mavenCentral()
}
}

Expand Down
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
27 changes: 18 additions & 9 deletions lib/build.gradle
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
plugins {
id 'com.android.library'
id 'kotlin-android'
id 'com.github.dcendents.android-maven'
id 'maven-publish'
}

group='com.github.li-yu'

android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
compileSdkVersion 31

defaultConfig {
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
targetSdkVersion 31

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
Expand All @@ -37,7 +34,19 @@ android {

dependencies {

implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testImplementation 'junit:junit:4.+'
api "androidx.datastore:datastore-preferences:1.0.0-alpha05"
api "androidx.datastore:datastore-preferences:1.0.0-rc01"
}

afterEvaluate {
publishing {
publications {
// Creates a Maven publication called "release".
release(MavenPublication) {
from components.release
groupId = 'com.github.li-yu'
artifactId = 'DataStoreExt'
version = '1.1.0'
}
}
}
}
Loading

0 comments on commit d5c117d

Please sign in to comment.