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

MutablePreferences

class MutablePreferences : Preferences
kotlin.Any
   ↳ androidx.datastore.preferences.Preferences
   ↳ androidx.datastore.preferences.MutablePreferences

Mutable version of Preferences. Allows for creating Preferences with different key-value pairs.

Summary

Public methods
Map<Preferences.Key<*>, Any>

Retrieve a map of all key preference pairs.

operator Boolean

Boolean
equals(other: Any?)

operator T?

Get a preference with a key.

Int

operator Unit
set(key: Preferences.Key<T>, value: T)

Set a key value pair in MutablePreferences.

String

For better debugging.

Extension functions
From androidx.datastore.preferences
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.

Inherited extension functions
From androidx.datastore.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.

Public methods

asMap

fun asMap(): Map<Preferences.Key<*>, Any>

Retrieve a map of all key preference pairs. The returned map is unmodifiable, and attempts to mutate it will throw runtime exceptions.

Return
a map containing all the preferences in this Preferences

contains

operator fun <T> contains(key: Preferences.Key<T>): Boolean

equals

fun equals(other: Any?): Boolean

get

operator fun <T> get(key: Preferences.Key<T>): T?

Get a preference with a key. If the key is not set, returns null.

If T is Set, this returns an unmodifiable set which will throw a runtime exception when mutated. Do not try to mutate the returned set.

Use MutablePreferences.set to change the value of a preference (inside a DataStore.edit block).

Parameters
T the type of the preference
key: Preferences.Key<T> the key for the preference
Exceptions
ClassCastException if there is something stored with the same name as key but it cannot be cast to T

hashCode

fun hashCode(): Int

set

operator fun <T> set(
    key: Preferences.Key<T>,
    value: T
): Unit

Set a key value pair in MutablePreferences.

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

// Once edit completes successfully, preferenceStore will contain the incremented counter. preferenceStore.edit { prefs: MutablePreferences -> prefs\[COUNTER_KEY\] = prefs\[COUNTER_KEY\] :? 0 + 1 }

Parameters
key: Preferences.Key<T> the preference to set
key: Preferences.Key<T> the value to set the preference to

toString

fun toString(): String

For better debugging.