咱们之前曾经 分享 了 Proto DataStore 和 Preferences DataStore 的应用办法。这两个 DataStore 版本都会在后盾应用 Protos 对数据进行序列化。您也能够应用 Kotlin 序列化,联合应用 DataStore 与自定义数据类。这有助于缩小样板代码,且无需学习或依赖于 Protobuf 库,同时仍能够为数据提供架构。
您须要实现以下几项操作:
- 定义数据类
- 确保您的数据类不可变
- 应用 Kotlin 序列化实现 DataStore 序列化器
- 开始应用
定义数据类
Kotlin 数据类 非常适合与 DataStore 联合应用,这是因为它们可能与 Kotlin 序列化无缝合作。DataStore 会依赖数据类主动生成的 equals
和 hashCode
。数据类也会生成便于调试和更新数据的 toString
和 copy
函数。
/* Copyright 2021 Google LLC. SPDX-License-Identifier: Apache-2.0 */data class UserPreferences( val showCompleted: Boolean, val sortOrder: SortOrder)
确保您的数据类不可变
确保您的数据类不可变是十分重要的,这是因为 DataStore 无奈兼容可变类型。联合应用可变类型与 DataStore 会导致难以捕捉的谬误和竞争条件。数据类并非肯定不可变。
Vars 是可变的,所以您应应用 vals 代替:
/* Copyright 2021 Google LLC. SPDX-License-Identifier: Apache-2.0 */data class MyData(- var num: Int+ val num: Int)- myObj.num = 5 // Fails to compile when num is val+ val newObj = myObj.copy(num = 5)
数组是可变的,所以您不应将其公开。
/* Copyright 2021 Google LLC. SPDX-License-Identifier: Apache-2.0 */data class MyData(- var num: IntArray)- myObj.num = 5 // This would mutate your object
即便将只读列表用作数据类的一部分,该数据类也仍为可变的。您应思考改用 不可变/长久化汇合:
/* Copyright 2021 Google LLC. SPDX-License-Identifier: Apache-2.0 */data class MyData(- val nums: List<Int>+ val nums: PersistentList<Int>)- val myInts = mutableListOf(1, 2, 3, 4)- val myObj = MyData(myInts)- myInts.add(5) // Fails to compile with PersistentList, but mutates with List+ val newData = myObj.copy(+ nums = myObj.nums.mutate { it += 5 } // Mutate returns a new PersistentList+ )
将可变类型用作数据类的一部分会令数据类变为可变状态。您不应采取上述做法,反而要确保所有内容都是不可变类型。
/* Copyright 2021 Google LLC. SPDX-License-Identifier: Apache-2.0 */ data class MyData(- val mutableType: MutableType) - val myType = MutableType()- val myObj = MyData(myType)- myType.mutate()
实现 DataStore 序列化器
Kotlin 序列化反对包含 JSON 和协定缓冲区在内的 多种格局。我将在此处应用 JSON,因为它非常常见、易于应用且会以明文模式进行存储,便于调试。Protobuf 也是一个不错的抉择,因为它规模更小、速度更快且兼容 protobuf-lite。
要应用 Kotlin 序列化读取数据类并将其写入 JSON,您须要应用 @Serializable
正文数据类并应用 Json.decodeFromString<YourType>(string)
和 Json.encodeToString(data)
。以下是带有 UserPreferences
的示例:
/* Copyright 2021 Google LLC. SPDX-License-Identifier: Apache-2.0 */ @Serializable data class UserPreferences( val showCompleted: Boolean = false, val sortOrder: SortOrder = SortOrder.None ) object UserPreferencesSerializer : Serializer<UserPreferences> { override val defaultValue = UserPreferences() override suspend fun readFrom(input: InputStream): UserPreferences { try { return Json.decodeFromString( UserPreferences.serializer(), input.readBytes().decodeToString()) } catch (serialization: SerializationException) { throw CorruptionException("Unable to read UserPrefs", serialization) } } override suspend fun writeTo(t: UserPreferences, output: OutputStream) { output.write(Json.encodeToString(UserPreferences.serializer(), t).encodeToByteArray()) }}
⚠️ 将 Parcelables 与 DataStore 一起应用并不平安,因为不同 Android 版本之间的数据格式可能会有所变动。
应用序列化器
在您构建时,将您创立的序列化器传递到 DataStore:
/* Copyright 2021 Google LLC. SPDX-License-Identifier: Apache-2.0 */val Context.dataStore by dataStore("my_file.json", serializer = UserPreferencesSerializer)
其读取数据看起来与应用 protos 进行读取一样:
/* Copyright 2021 Google LLC. SPDX-License-Identifier: Apache-2.0 */suspend fun getShowCompleted(): Boolean { context.dataStore.data.first().showCompleted}
您能够应用生成的 .copy() 函数更新数据:
/* Copyright 2021 Google LLC. SPDX-License-Identifier: Apache-2.0 */suspend fun setShowCompleted(newShowCompleted: Boolean) { // This will leave the sortOrder value untouched: context.dataStore.updateData { it.copy(newShowCompleted = showCompleted) }}
总结
联合应用 DataStore 与 Kotlin 序列化和数据类可缩小样板文件并有助于简化代码,但您必须多加小心,防止因为可变性而引发谬误。您只需定义数据类和实现序列化器即可。快来入手尝试一下吧!
如要具体理解 DataStore,您能够查看咱们的 文档 并取得一些应用 Proto DataStore 和 Preferences DataStore Codelab 的实践经验。