DataStore Preferences
DataStore Preferences is a persistent key-value data storage solution offered by Android Jetpack. It provides a lightweight and asynchronous approach to storing and retrieving small amounts of structured data within your Android applications.
Usage
Dependencies
Within your app
module’s build.gradle.kts
file, incorporate the following dependencies:
implementation(project(":datastore"))
Example
We provide you with DataStorePreferences
class that serves as a foundation for building your custom DataStorepreferences . You can extend this class to create specific preferences for your app.
class ExamplePreferences(context: Context): DataStorePreferences(context, "example_preferences") {
val testValueOrNull = getOrNull(PreferencesKeys.testKey)
val testValueOrDefault = getOrDefault(PreferencesKeys.testKey, "default")
suspend fun setTestValue(value: String) {
set(PreferencesKeys.testKey, value)
}
private object PreferencesKeys {
val testKey = stringPreferencesKey("test_key")
}
}
The DataStorePreferences constructor accepts a name
parameter, allowing you to customize the name of the preferences file. It also requires the context
parameter to be able to create a DataStore File.
Furthermore it provides a few helper methods to store and retrieve data from the DataStore file.
set(key: Preferences.Key<T>, value: T)
: This method allows you to store a value in the DataStore file for the given key.getOrNull(key: Preferences.Key<T>): Flow<T?>
: This method allows you to retrieve a value from the DataStore file for the given key. It returns a Flow of the value so you can observe changes in the value. If the value is not found it returns null.getOrDefault(key: Preferences.Key<T>, defaultValue: T): Flow<T>
: This method allows you to retrieve a value from the DataStore file for the given key. It returns a Flow of the value so you can observe changes in the value. If the value is not found it returns the default value provided.
More information on DataStore Preferences can be found in the official documentation .