Ever since the release of Android Jetpack it has come up with several libraries which makes us writing better Android code, avoid boilerplate code, etc. and now this time it has brought us an another awesome library called DataStore which according to official blog aims to replace the SharedPreferences API which has several drawbacks.
自从Android Jetpack发行以来,它已经提供了几个库,这使我们能够编写更好的Android代码,避免样板代码等。现在,这一次它为我们带来了另一个名为DataStore出色库,据官方博客旨在替换SharedPreferences API有几个缺点。
DataStore is a storage solution which is built on Coroutines and Flow to store data asynchronously. DataStore allows us to either store data in key-value pairs much like SharedPreferences or in typed objects which are backed by protocol buffers.
DataStore是基于Coroutines和Flow构建的存储解决方案,用于异步存储数据。 DataStore允许我们将数据存储在类似于SharedPreferences的键值对中,或者存储在协议缓冲区支持的类型化对象中。
DataStore provides asynchronous API for storing and reading data, while SharedPreferences provides async API only while reading changed values with the use of listeners.
DataStore提供异步API用于存储和读取数据,而SharedPreferences仅在使用侦听器读取更改的值时提供异步API。
DataStore is safe to call on the UI thread. It uses Dispatchers.IO under the hood.
可以安全地在UI线程上调用DataStore 。 它在后台使用Dispatchers.IO 。
DataStore is safe from runtime exceptions, while SharedPreferences can throw parsing errors in runtime exceptions.
DataStore不受运行时异常的影响,而SharedPreferences可以在运行时异常中引发解析错误。
Proto DataStore provides better type safety out of the box.
Proto DataStore开箱即用,可提供更好的类型安全性。
Android Developers Blog Android开发者博客Jetpack provides two implementations of DataStore:
Jetpack提供了两种DataStore实现:
Preferences DataStore— It stores data in a key-value pairs like SharedPreferences but does not provide any type safety.
首选项数据存储-将数据存储在键值对(如SharedPreferences但不提供任何类型安全性。
Proto DataStore — It store data as custom objects. It provides type safety out of the box, but it requires you to specify a scheme using protocol buffers.
Proto DataStore-将数据存储为自定义对象。 它提供了开箱即用的类型安全性,但是它要求您使用协议缓冲区指定方案。
In this article we will learn about the Preferences DataStore.
在本文中,我们将了解Preferences DataStore。
As working with any library, first you need to add a dependency in your app level build.gradle file.
与任何库一起使用时,首先需要在应用程序级别的build.gradle文件中添加一个依赖build.gradle 。
dependencies { // Preferences DataStore implementation "androidx.datastore:datastore-preferences:1.0.0-alpha01"}Currently, the DataStore library is in the alpha stage, but you can always get the latest version from the official docs.
目前, DataStore库处于Alpha阶段,但您始终可以从官方docs获取最新版本。
Suppose you are creating a music application and you want to save the id of the last music played by the user, so that the user can find the last played song when he opens the app again after some time.
假设您正在创建一个音乐应用程序,并且想要保存用户最近播放的音乐的ID,以便用户在一段时间后再次打开该应用程序时可以找到该用户最近播放的歌曲。
For this, we will create a class MusicPreferences where we will handle all the preferences set by the user.
为此,我们将创建一个MusicPreferences类,其中将处理用户设置的所有首选项。
class MusicPreferences(private val context: Context) { private val dataStore: DataStore<Preferences> = context.createDataStore( name = "music_pref" ) companion object{ val LAST_PLAYED_SONG_KEY = preferencesKey<Int>(name = "last_Played_song") } suspend fun saveLastPlayedSong(id: Int){ dataStore.edit { preferences -> preferences[LAST_PLAYED_SONG_KEY] = id } } val lastPlayedSong: Flow<Int> = dataStore.data .map { preferences -> preferences[LAST_PLAYED_SONG_KEY] ?: -1 } }The MusicPreferences class will require the Context object to create the DataStore.
MusicPreferences类将需要Context对象创建DataStore 。
We can create our DataStore with the .createDataStore() extension function of the Context object. We need to set the name of our datastore with the mandatory name parameter.
我们可以使用Context对象的.createDataStore()扩展功能创建DataStore 。 我们需要使用强制name参数设置数据存储的name 。
You need to define a key for each value to save with the Preferences.preferencesKey() function. You also need to define the name of the key with name parameter.
您需要为每个值定义一个键,以使用Preferences.preferencesKey()函数进行保存。 您还需要使用name参数定义键的name 。
We can create a function to save the song id in the DataStore. The DataStore provides a edit() method to save the value. We can pass the key and value to the MutablePreferences in the trailing lambda. Note that the edit() function is a suspend function.
我们可以创建一个函数来将歌曲ID保存在DataStore 。 DataStore提供了edit()方法来保存值。 我们可以将键和值传递给尾随lambda中的MutablePreferences 。 请注意, edit()函数是一个suspend函数。
Now you can get the saved preferences from the datastore with datastore.data which returns a Flow<Preferences> and with the .map{} operator we can can get the Flow<Int> which is our song id by passing the right key into the preferences.
现在,您可以使用datastore.data从数据存储中获取保存的首选项,该Flow<Preferences>返回Flow<Preferences>并使用.map{}运算符,可以通过向右传递键来获取Flow<Int>这是我们的歌曲ID。优先。
Now in your ViewModel or activity/fragment whenever you want to save the song id into the DataStore, you just need to call our suspend function saveLastPlayedSongID() from a coroutine.
现在,只要您想将歌曲ID保存到DataStore ,就可以在ViewModel或活动/片段中,只需从协程调用我们的暂停函数saveLastPlayedSongID() 。
class MusicViewModel( private val repository: MusicRepository ) : ViewModel{ viewModelScope.launch { musicPreferences.saveLastPlayedSong(song.id) } }In order to get the saved song id in the activity from the DataStore we can change the get the Flow<Int> and observe it after changing to LiveData with .asLiveData().
为了从DataStore获得活动中保存的歌曲ID,我们可以更改get Flow<Int>并在使用.asLiveData()更改为LiveData之后对其进行.asLiveData() 。
musicPreferences.lastPlayedSong.asLiveData().observe(this){ id -> lastPlayedSong = repository.getSong(id) }Now, as we have exposed the song id as a Flow, it will emit the values each time the song id is updated or edited in the datastore and the last played song will be updated accordingly.
现在,由于我们将歌曲ID公开为Flow ,因此每次在数据存储区中更新或编辑歌曲ID时,它将发出值,并且最后播放的歌曲将相应地更新。
The DataStore library comes up with many benefits over the SharedPreferences API such as supporting coroutines and flows. It reads and writes the data asynchronously which makes it safe to call on the UI thread and it also has an error signalling mechanism, whereas SharedPreferences has several drawbacks such as not safe to call on the UI thread and has an asynchronous API. DataStore is an excellent replacement that solves most of the problems with SharedPreferences.
与SharedPreferences API相比, DataStore库具有许多优势,例如支持协程和流程。 它异步读取和写入数据,这使得在UI线程上可以安全调用,并且还具有错误信号通知机制,而SharedPreferences具有一些缺点,例如在UI线程上不能安全调用,并且具有异步API。 DataStore是一个出色的替代产品,可以解决SharedPreferences大多数问题。
翻译自: https://proandroiddev.com/lets-explore-jetpack-datastore-in-android-621f3564b57
相关资源:微信小程序源码-合集6.rar