Sobes.tech
Junior — Middle

What methods can be used to interact with DataStore in an application?

sobes.tech AI

Answer from AI

In Android, there are two main approaches to interact with DataStore:

  1. Preferences DataStore — stores key-value pairs, suitable for simple settings.

    • Used via the DataStore<Preferences> object.
    • Reading and writing are done using keys of type Preferences.Key<T>.
  2. Proto DataStore — stores structured data in the form of protobuf messages.

    • Requires defining a protobuf schema.
    • Allows storing complex data types with validation.

Interaction methods:

  • Reading — through Flow, e.g., dataStore.data.map { preferences -> ... }, which allows reacting to data changes.
  • Writing — through the suspend function dataStore.edit { preferences -> ... }, where values can be modified.

Example of reading and writing Preferences DataStore:

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

val EXAMPLE_KEY = stringPreferencesKey("example_key")

// Writing
suspend fun saveExample(value: String) {
    context.dataStore.edit { preferences ->
        preferences[EXAMPLE_KEY] = value
    }
}

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

Thus, interaction with DataStore is built on using Flow for reading and suspend functions for writing.