Write Data to DataStore

In this section, you’ll learn how to write data to DataStore.

You need keys to write data to DataStore. Creating keys to store data in DataStore is easier as DataStore library comes with some built-in functions to create keys for different data types. Examples include:

  • stringPreferencesKey(name: String): Creates a key for a string value.
  • intPreferencesKey(name: String): Creates a key for an integer value.
  • floatPreferencesKey(name: String): Creates a key for a float value.
  • booleanPreferencesKey(name: String): Creates a key for a Boolean value.
  • longPreferencesKey(name: String): Creates a key for a long value.
  • doublePreferencesKey(name: String): Creates a key for a double value.
  • stringSetPreferencesKey(name: String): Creates a key for a set of strings.
  • byteArrayPreferencesKey(name: String): Creates a key for a byte array.

All the functions take a name parameter that’s used to create a unique key for your data type. Note that this doesn’t provide type safety, so you need to ensure that you use the correct key and type when reading and writing data.

Writing data to DataStore has to be in a suspending function. This is because DataStore performs I/O operations, and you need to call it from a coroutine. An example of writing data to DataStore is shown below:

suspend fun saveSelectedFilter(selectedFilter: String) {
  val dataStoreKey = stringPreferencesKey("filters")
  context.dataStore.edit { preferences ->
    preferences[dataStoreKey] = selectedFilter
  }
}

In the above example, you create a dataStoreKey variable using the stringPreferencesKey() function. This function creates a Preference.Key<String> instance. You then call dataStore.edit(), which takes in a lambda that provides access to a mutable class of Preferences that allows you to save your key-value pairs. Inside the lambda, you set the selectedFilter to the dataStoreKey. This will save the selected filter to DataStore.

Editing data in DataStore is an atomic read-modify-write operation. This means that when you edit data in DataStore, it’s guaranteed that the data will be updated atomically. When a write operation is in progress, data is locked for other threads until the write operation is complete. This ensures that your data is consistent and that no data corruption occurs. If the write operation fails, the transaction is aborted, and exceptions are thrown.

To handle errors when writing data to DataStore, you can use Kotlin’s try-catch block. This is useful when you want to handle exceptions that occur during the write operation. For example, if you’re writing data to DataStore and the operation fails, you can catch the exception and handle it gracefully. An example of error handling when writing data to DataStore is shown below:

suspend fun saveSelectedFilter(selectedFilter: String) {
  val dataStoreKey = stringPreferencesKey("filters")
  try {
    context.dataStore.edit { preferences ->
      preferences[dataStoreKey] = selectedFilter
    }
  } catch (e: Exception) {
    // Handle the exception
  }
}
See forum comments
Download course materials from Github
Previous: Demo: Create & Setup DataStore Next: Demo: Write Data to DataStore