jetpack数据库_使用jetpack数据存储使您的手变脏

jetpack数据库

In the previous blog, I have talked about what Datastore is, why it is created and also made a quick comparison with SharePreference. In this blog, we will see how to implement it.

上一篇博客中,我讨论了什么是数据存储,为什么要创建它,并与SharePreference进行了快速比较。 在此博客中,我们将看到如何实现它。

组态 (Configuration)

First, we need to configure some dependencies and plugins to our project.

首先,我们需要为项目配置一些依赖项和插件。

Add this plugin on top of build.gradle file of the desired module:

将此插件添加到所需模块的build.gradle文件之上:

plugins {id "com.google.protobuf" version "0.8.12"
}

Next, add the protobuf convention to the same build.gralde file:

接下来,将protobuf约定添加到相同的build.gralde文件中:

protobuf {protoc {artifact = "com.google.protobuf:protoc:3.10.0"
}
generateProtoTasks {all().each { task ->task.builtins {java {option 'lite'
}
}
}
}
}

And then this dependency:

然后这个依赖:

implementation  "com.google.protobuf:protobuf-javalite:3.10.0"

All these plugin, convention and library will help to generate java code from protobuf schema.

所有这些插件,约定和库将有助于从protobuf模式生成Java代码。

And now, we add datastore libraries to the project:

现在,我们将数据存储库添加到项目中:

// Preferences DataStore
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha01"
// Proto DataStore
implementation "androidx.datastore:datastore-core:1.0.0-alpha01"

Additionally, you will need to specify jvmTarget to java version 1.8 to be able to build some inline functions.

此外,您将需要将jvmTarget指定为Java版本1.8,以便能够构建一些内联函数。

kotlinOptions {jvmTarget = JavaVersion.VERSION_1_8.toString()
}

Your build.gradle file will finally look like this:

您的build.gradle文件最终将如下所示:

plugins {
    id "com.google.protobuf" version "0.8.12"
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'


dependencies {
    //protobuf
    implementation  "com.google.protobuf:protobuf-javalite:3.10.0"
    // datastore
    // Preferences DataStore
    implementation "androidx.datastore:datastore-preferences:1.0.0-alpha01"
    // Proto DataStore
    implementation "androidx.datastore:datastore-core:1.0.0-alpha01"
}


android {
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
}


protobuf {
    protoc {
        artifact = "com.google.protobuf:protoc:3.10.0"
    }


    // Generates the java Protobuf-lite code for the Protobufs in this project. See
    // https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
    // for more information.
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                java {
                    option 'lite'
                }
            }
        }
    }
}

You may also want to install Protocol Buffer Editor plugin to support formatting .proto files.

您可能还需要安装Protocol Buffer Editor插件以支持格式化.proto文件。

首选项数据存储 (Preference Datastore)

1.创建数据存储(1. Create Datastore)

We need to create a reference of Datastor using an extension method of Context.

我们需要使用Context的扩展方法来创建Datastor的引用。

//for Preference Datastore
const val PREF_DATASTORE_NAME = "PREF_DATASTORE_NAME"
val datastore : createDataStore(name = PREF_DATASTORE_NAME
)

PREFERENCE_DATASTORE_NAME will be the name of the storage file. In this createDataStore() function, you can also put a CoroutineScope to define the scope in which operations will be executed. A scope with IO dispatchers is used by default.

PREFERENCE_DATASTORE_NAME将是存储文件的名称。 在此createDataStore() 函数,您还可以放置CoroutineScope定义将在其中执行操作的范围。 默认情况下,使用带有IO调度程序的作用域。

If you are using SharePreference and want to migrate from it, you can pass a SharedPreferencesMigration to the function:

如果您正在使用SharePreference并希望从中迁移,则可以将SharedPreferencesMigration传递给该函数:

const val OLD_SHAREPREFERENCE_NAME = "OLD_SHAREPREFERENCE_NAME"
val datastore = context.createDataStore(name = PREF_DATASTORE_NAME,
migrations = listOf(SharedPreferencesMigration(context, OLD_SHAREPREFERENCE_NAME))
)

2.读取数据 (2. Read data)

val SETTING_KEY = preferencesKey<String>("SETTING_KEY")val settingFlow  : Flow<String> = datastore.data.map {it[SETTING_KEY] ?: "" //this is not type-safe
}

3.写入数据 (3. Write data)

suspend fun setSetting(setting : String) {datastore.edit {it[SETTING_KEY] = setting
}}

原始数据存储 (Proto Datastore)

1.定义架构。(1. Define the schema.)

Suppose that we want to store a User object to Datastore, we have to define the schema for the User type. In the app/src/main/proto/ directory, create a User.proto file.

假设我们想将User对象存储到Datastore,我们必须为User类型定义架构。 在app / src / main / proto /目录中,创建一个User.proto文件。

syntax = "proto3";

//define the package where User will be located after being generated
option java_package = "com.example.datastore";
option java_multiple_files = true;

message User {string firstname = 1;
string lastname = 2;
string email = 3;
string id = 4;
}

Then create a Serializer for User type.

然后为用户类型创建一个序列化程序。

object UserSerializer : Serializer<User> {
override fun readFrom(input: InputStream): User {
return try {
User.parseFrom(input)
} catch (exception: InvalidProtocolBufferException) {
throw CorruptionException("Cannot read proto.", exception)
}
}

override fun writeTo(t: User, output: OutputStream) {
t.writeTo(output)
}
}

Now that everything is ready, let’s create a datastore.

现在一切就绪,让我们创建一个数据存储。

2.创建数据存储 (2. Create datastore)

//for Proto Datastore
val userDatastore : DataStore<User> = createDataStore(fileName = "user.pb",
serializer = UserSerializer
)

Similar to creating a preference datastore, we have the option to provide a CoroutineScope or a SharePreference migration.

与创建首选项数据存储类似,我们可以选择提供CoroutineScopeSharePreference迁移。

3.读取数据 (3. Read data)

val userFlow : Flow<User> = datastore.data

4.写入数据 (4. Write data)

To write a whole new data:

要写入全新数据:

suspend fun storeUser(user : User) {
userDatastore.updateData {user.toBuilder().build()
}}

Or to update partially data:

或部分更新数据:

suspend fun updateUserEmail(newEmail : String) {
userDatastore.updateData { user ->user.toBuilder().setEmail(newEmail).build()
}
}

That’s all for the implementation of Datastore. It requires a bit of extra work compared to SharePreference.

这就是数据存储区的全部实现。 与SharePreference相比,它需要一些额外的工作。

数据如何持久保存? (How is data persisted?)

1. SharePreference (1. SharePreference)

As you already know (or may not know), SharePreference uses xml to persist data. It creates a .xml files in the /data/data/{application.package}/shared_prefsdirectory and stores all the key-value pairs. The name of these files is defined by the argument name of the function getSharedPreferences() . Opening the files, we will have something similar to this:

如您所知(或可能不知道), SharePreference使用xml来保留数据。 它在/data/data/{application.package}/shared_prefs目录中创建一个.xml文件,并存储所有键值对。 这些文件的名称由函数getSharedPreferences()的参数名称定义。 打开文件,我们将具有以下类似内容:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<
map>
<
string name="app_name">Datastore sample</string>
</
map>

Of course the files are inaccessible from outside of the application. Without a rooted device or an emulator, we can not open to see them.

当然,无法从应用程序外部访问文件。 没有生根的设备或仿真器,我们将无法打开查看它们。

2. Jetpack数据存储 (2. Jetpack Datastore)

The protobuf files will be located in /data/data/{application.package}/files/datastore/ . These are the protobuf formatted files, so we can not read them with an ordinary editor. To decode the files, we can use protoc command line.

protobuf文件将位于/ data/data/{application.package}/files/datastore/ 。 这些是protobuf格式的文件,因此我们无法使用普通编辑器读取它们。 要解码文件,我们可以使用协议 命令行。

To be able to use protoc command, we have to pull these files to our workstation’s space using adb command

为了能够使用protoc命令,我们必须使用adb命令将这些文件拉到工作站的空间

  • For preference datastore

    对于首选项数据存储
protoc --decode_raw < app_name.preferences_pb

The result will be similar to this:

结果将类似于以下内容:

1 {
1: "app_name"
2 {5: "Datastore sample"
}
}
1 {
1: "is_demo_mode"
2 {1: 1
}
}

Note: value 1 of is_demo_mode represents a true

注意: is_demo_mode1代表true

  • For proto datastore

    对于原始数据存储
protoc --decode_raw < user.pb

We will get this as the result:

我们将得到以下结果:

1: "lam"
2: "pham"
3: "lam@email.com"

有关数据存储的第一印象 (First impressions about Datastore)

  • Google applies Kotlin Coroutine to do an asynchronous task → Is this an official death announcement for RxJava?

    Google应用Kotlin Coroutine执行异步任务→这是RxJava的正式死亡公告吗?
  • Will Proto Buffers be a promising data format for future Android libraries?

    Proto Buffers是否会成为未来Android库的有前途的数据格式?

  • The implementation is a bit complex for a small job.

    对于少量工作,实现有些复杂。
  • An independent schema system besides POJO classes will confuse the codes or add a mapping layer.

    除了POJO类之外,独立的模式系统还会使代码混乱或添加映射层。

Lam PHAM

林彭

翻译自: https://medium.com/swlh/get-your-hand-dirty-with-jetpack-datastore-b1f1dfb0a5c1

jetpack数据库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值