I found a new thing while wandering around, and I want to share it with you.
SharedPreferences Everyone should have used it, it has a lot of slots, so much that I wrote a special article.
Count the SharedPreferences slots!
However, official ridicule is the most deadly.
- Synchronous API encourages StrictMode violations
- apply() and commit() have no mechanism of signalling errors
- apply() will block the UI thread on fsync()
- Not durable – it can return state that is Not yet persisted
- No consistency or transactional semantics
- Throws runtime exception on parsing errors
- Exposes mutable references to its internal state
I will not translate, it may not be very accurate. AndroidX has added a new member to the DataStore class.
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:datastore/datastore-core/src/main/kotl in/androidx/datastore/DataStore.kt
What is DataStore?
So what is DataStore?
DataStore provides a safe and durable way to store small amounts of data, such as preferences and application state. It does not support partial updates: if any field is modified, the whole object will be serialized and persisted to disk. If you want partial updates, consider the Room API (SQLite).
DataStore provides ACID guarantees. It is thread-safe, and non-blocking. In particular, It addresses these design shortcomings of the SharedPreferences API.
I can translate this.
DataStore provides a secure and stable solution for storing lightweight data, such as configuration files and application status. It does not support local updates: if any member variable is modified, the entire object will be serialized and persisted to disk. For partial modifications, consider using Room.
DataStore guarantees atomicity, consistency, isolation, and persistence. It is thread-safe and non-blocking. In particular, it addresses a design flaw in the SharedPreferences API.
Boy, looks like this is a replacement for SharedPreferences.
In the code
Take a quick look at the code implementation.
DataStore is an interface.
interface DataStore<T> {
val dataFlow: Flow<T>
suspend fun updateData(transform: suspend (t: T) - >T): T
interface Serializer<T> {
fun readFrom(input: InputStream): T
fun writeTo(t: T, output: OutputStream)
val defaultValue: T
}
// TODO(b/151635324): Add initializers.
// TODO(b/151635324): Add exception handlers.
// TODO(b/151635324): Consider adding snapshot API.
}
Copy the code
That’s right, it’s based on coroutines and Flow.
dataFlow
Is a Flow objectupdateData()
Used to update objectsSerializer
Interface to provide serialization and persistence capabilities
Currently, only one implementation class is provided in the source code: SingleProcessDataStore. As the name suggests, multiple processes are not supported. Take a look at some of the key methods.
class SingleProcessDataStore<T>(
private val produceFile: () -> File,
private val serializer: DataStore.Serializer<T>,
private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
) : DataStore<T> {
.
private suspend fun readData(a): T {
// TODO(b/151635324): consider caching produceFile result.
val file = produceFile()
try {
FileInputStream(file).use { stream ->
return serializer.readFrom(stream)
}
} catch (ex: FileNotFoundException) {
if (file.exists()) {
throw ex
}
return serializer.defaultValue
}
}
private fun writeData(newData: T) {
// TODO(b/151635324): consider caching produceFile result.
val file = produceFile()
file.mkdirs()
val scratchFile = File(file.absolutePath + SCRATCH_SUFFIX)
try {
FileOutputStream(scratchFile).use { stream ->
serializer.writeTo(newData, stream)
stream.fd.sync()
// TODO(b/151635324): fsync the directory, otherwise a badly timed crash could
// result in reverting to a przuihouevious state.
}
scratchFile.renameTo(file)
} catch (ex: IOException) {
if (scratchFile.exists()) {
scratchFile.delete()
}
throw ex
}
}
.
}
Copy the code
Both readData() and writeData() are actually reading and writing files.
Specific usage can be found in the official writing unit tests SingleProcessDataStoreTest, address the following:
https://cs.android.com/androidx/platform/frameworks/support/+/androidx-master-dev:datastore/datastore-core/src/test/kotl in/androidx/datastore/SingleProcessDataStoreTest.kt
The last
As of now, DataStore is still under development and has not been released in any usable version, which is not a good enough replacement for SharedPreferences at this time. According to Google urinalysis, it’s not surprising to have a miscarriage one day. You can keep an eye on it in Androidx-master-dev.
But two things are certain.
First, Google itself is getting tired of SharedPreferences.
Second, more and more new features are implemented based on Kotlin, or even Kotlin Only. There is a trend from Kotlin First to Kotlin Only.
So, for those of you who haven’t learned Kotlin yet, get on the bus!
Today’s article is here, I have been adhering to the original bingxin said, more latest Android dynamic, scan code to pay attention to my public number!
This article is formatted using MDNICE