Sobes.tech
Junior — Middle

How to implement storage of constant key-value pairs in DataStore?

sobes.tech AI

Answer from AI

In Android, it is recommended to use DataStore for storing persistent key-value pairs — a modern alternative to SharedPreferences.

For storing persistent data, you can use Proto DataStore or Preferences DataStore. For simple key-value pairs, Preferences DataStore is suitable.

Example of using Preferences DataStore:

val Context.dataStore by preferencesDataStore(name = "settings")

// Key for storing the value
val EXAMPLE_KEY = stringPreferencesKey("example_key")

// Saving a value
suspend fun saveExampleValue(context: Context, value: String) {
    context.dataStore.edit { preferences ->
        preferences[EXAMPLE_KEY] = value
    }
}

// Reading the value
val exampleFlow: Flow<String?> = context.dataStore.data
    .map { preferences ->
        preferences[EXAMPLE_KEY] ?: "default"
    }

Thus, DataStore provides asynchronous, thread-safe, and reliable storage of key-value pairs.