Google is committed to advancing racial equity for Black communities. See how.

androidx.datastore.preferences

Classes

MutablePreferences

Mutable version of Preferences.

Preferences

Preferences and MutablePreferences are a lot like a generic Map and MutableMap keyed by the Preferences.

Top-level functions summary

SharedPreferencesMigration<Preferences>
SharedPreferencesMigration(context: Context, sharedPreferencesName: String, keysToMigrate: Set<String>? = MIGRATE_ALL_KEYS, deleteEmptyPreferences: Boolean = true)

Creates a SharedPreferencesMigration for DataStore.

Preferences

Get a new empty Preferences.

MutablePreferences

Construct a MutablePreferences object with a list of Preferences.

Preferences.Key<T>

Get a preference Key of type T.

Preferences
preferencesOf(vararg pairs: Preferences.Pair<*>)

Construct a Preferences object with a list of Preferences.

Preferences.Key<Set<T>>

Get a preference key for Set.

Extension functions summary

For android.content.Context
DataStore<Preferences>
Context.createDataStore(name: String, corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null, migrations: List<DataMigration<Preferences>> = listOf(), scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()))

Create an instance of SingleProcessDataStore.

For MutablePreferences
Unit

operator Unit

Removes the preference with the given key from this MutablePreferences.

operator Unit

Appends or replaces all pairs from prefs to this MutablePreferences.

operator Unit

Appends or replaces all pair to this MutablePreferences.

Unit

Appends or replaces all pairs to this MutablePreferences.

T

Remove a preferences from this MutablePreferences.

For DataStore
suspend Preferences
DataStore<Preferences>.edit(transform: suspend (MutablePreferences) -> Unit)

Edit the value in DataStore transactionally in an atomic read-modify-write operation.

For Key
infix Preferences.Pair<T>
Preferences.Key<T>.to(value: T)

Infix function to create a Preferences.

For Preferences
MutablePreferences

Gets a mutable copy of Preferences which contains all the preferences in this Preferences.

Preferences

Gets a read-only copy of Preferences which contains all the preferences in this Preferences.

Top-level functions

SharedPreferencesMigration

@JvmOverloads fun SharedPreferencesMigration(
    context: Context,
    sharedPreferencesName: String,
    keysToMigrate: Set<String>? = MIGRATE_ALL_KEYS,
    deleteEmptyPreferences: Boolean = true
): SharedPreferencesMigration<Preferences>

Creates a SharedPreferencesMigration for DataStore.

Parameters
context: Context Context used for getting SharedPreferences.
sharedPreferencesName: String The name of the SharedPreferences.
keysToMigrate: Set<String>? = MIGRATE_ALL_KEYS The list of keys to migrate. The keys will be mapped to datastore.Preferences with their same values. If the key is already present in the new Preferences, the key will not be migrated again. If the key is not present in the SharedPreferences it will not be migrated. If keysToMigrate is not set, all keys will be migrated from the existing SharedPreferences.
deleteEmptyPreferences: Boolean = true

If enabled and the SharedPreferences are empty (i.e. no remaining keys) after this migration runs, the leftover SharedPreferences file is deleted. Note that this cleanup runs only if the migration itself runs, i.e., if the keys were never in SharedPreferences to begin with then the (potentially) empty SharedPreferences won't be cleaned up by this option. This functionality is best effort - if there is an issue deleting the SharedPreferences file it will be silently ignored.

TODO(rohitsat): determine whether to remove the deleteEmptyPreferences option.

emptyPreferences

fun emptyPreferences(): Preferences

Get a new empty Preferences.

Return
a new Preferences instance with no preferences set

mutablePreferencesOf

fun mutablePreferencesOf(vararg pairs: Preferences.Pair<*>): MutablePreferences

Construct a MutablePreferences object with a list of Preferences.Pair. Comparable to mapOf().

Example usage:

val counterKey = preferencesKey("counter") val preferences = preferencesOf(counterKey to 100)

Parameters
vararg pairs: Preferences.Pair<*>

preferencesKey

inline fun <reified T : Any> preferencesKey(name: String): Preferences.Key<T>

Get a preference Key of type T. Type T must be one of: Int, Long, Boolean, Float, String. Use the preferencesSetKey function to create a preference key for Set. No other types are supported.

You should not have multiple keys with the same name (for use with the same Preferences). Using overlapping keys with different types will result in ClassCastExceptions.

Return
the Preference.Key object for your preference
Exceptions
IllegalArgumentException if an unsupported type is used

preferencesOf

fun preferencesOf(vararg pairs: Preferences.Pair<*>): Preferences

Construct a Preferences object with a list of Preferences.Pair. Comparable to mapOf().

Example usage:

val counterKey = preferencesKey("counter") val preferences = preferencesOf(counterKey to 100)

Parameters
vararg pairs: Preferences.Pair<*>

preferencesSetKey

inline fun <reified T : Any> preferencesSetKey(name: String): Preferences.Key<Set<T>>

Get a preference key for Set. The only type currently supported for T is String.

Note: sets returned by DataStore are unmodifiable.

Exceptions
IllegalArgumentException if an unsupported type is used
Return
the Preference.Key object for use with Preferences

Extension functions

clear

fun MutablePreferences.clear(): Unit

createDataStore

fun Context.createDataStore(
    name: String,
    corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null,
    migrations: List<DataMigration<Preferences>> = listOf(),
    scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
): DataStore<Preferences>

Create an instance of SingleProcessDataStore. The user is responsible for ensuring that there is never more than one instance of SingleProcessDataStore acting on a file at a time.

Parameters
name: String The name of the preferences. The preferences will be stored in a file obtained by calling: File(context.filesDir, "datastore/" + name + ".preferences_pb")
corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null The corruptionHandler is invoked if DataStore encounters a CorruptionException when attempting to read data. CorruptionExceptions are thrown by serializers when data can not be de-serialized.
migrations: List<DataMigration<Preferences>> = listOf() are run before any access to data can occur. Each producer and migration may be run more than once whether or not it already succeeded (potentially because another migration failed or a write to disk failed.)
scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) The scope in which IO operations and transform functions will execute.

edit

suspend fun DataStore<Preferences>.edit(transform: suspend (MutablePreferences) -> Unit): Preferences

Edit the value in DataStore transactionally in an atomic read-modify-write operation. All operations are serialized.

The coroutine completes when the data has been persisted durably to disk (after which DataStore.data will reflect the update). If the transform or write to disk fails, the transaction is aborted and an exception is thrown.

Note: values that are changed in transform are NOT updated in DataStore until after the transform completes. Do not assume that the data has been successfully persisted until after edit returns successfully.

Note: do NOT store a reference to the MutablePreferences provided to transform. Mutating this after transform returns will NOT change the data in DataStore. Future versions of this may throw exceptions if the MutablePreferences object is mutated outside of transform.

See DataStore.updateData.

Example usage: val COUNTER_KEY = preferencesKey("my_counter")

dataStore.edit { prefs -> prefs\[COUNTER_KEY\] = prefs\[COUNTER_KEY\] :? 0 + 1 }

Parameters
transform: suspend (MutablePreferences) -> Unit block which accepts MutablePreferences that contains all the preferences currently in DataStore. Changes to this MutablePreferences object will be persisted once transform completes.
Exceptions
IOException when an exception is encountered when writing data to disk
Exception when thrown by the transform block

minusAssign

operator fun MutablePreferences.minusAssign(key: Preferences.Key<*>): Unit

Removes the preference with the given key from this MutablePreferences. If this Preferences does not contain the key, this is a no-op.

Example usage: mutablePrefs -= COUNTER_KEY

Parameters
key: Preferences.Key<*> the key to remove from this MutablePreferences

plusAssign

operator fun MutablePreferences.plusAssign(prefs: Preferences): Unit

Appends or replaces all pairs from prefs to this MutablePreferences. Keys in prefs will overwrite keys in this Preferences.

Example usage: mutablePrefs += preferencesOf(COUNTER_KEY to 100, NAME to "abcdef")

Parameters
prefs: Preferences Preferences to append to this MutablePreferences

plusAssign

operator fun MutablePreferences.plusAssign(pair: Preferences.Pair<*>): Unit

Appends or replaces all pair to this MutablePreferences.

Example usage: mutablePrefs += COUNTER_KEY to 100

Parameters
pair: Preferences.Pair<*> the Preference.Pair to add to this MutablePreferences

putAll

fun MutablePreferences.putAll(vararg pairs: Preferences.Pair<*>): Unit

Appends or replaces all pairs to this MutablePreferences.

Parameters
vararg pairs: Preferences.Pair<*> the pairs to append to this MutablePreferences

remove

fun <T> MutablePreferences.remove(key: Preferences.Key<T>): T

Remove a preferences from this MutablePreferences.

Parameters
key: Preferences.Key<T> the key to remove this MutablePreferences
Return
the original value of this preference key.

to

infix fun <T> Preferences.Key<T>.to(value: T): Preferences.Pair<T>

Infix function to create a Preferences.Pair. This is used to support preferencesOf and MutablePreferences.putAll

Parameters
value: T is the value this preferences key should point to.

toMutablePreferences

fun Preferences.toMutablePreferences(): MutablePreferences

Gets a mutable copy of Preferences which contains all the preferences in this Preferences. This can be used to update your preferences without building a new Preferences object from scratch in DataStore.updateData.

This is similar to Map.toMutableMap.

Return
a MutablePreferences with all the preferences from this Preferences

toPreferences

fun Preferences.toPreferences(): Preferences

Gets a read-only copy of Preferences which contains all the preferences in this Preferences.

This is similar to Map.toMap.

Return
a copy of this Preferences