Sher Sanginov
Sher Sanginov

Reputation: 595

How to listen to the success or failure result of writing to Preferences DataStore?

Preferences DataStore provides an edit() function that transactionally updates the data in a DataStore. For example, this function's transform parameter accepts a block of code where you can update the values as needed.

suspend fun incrementCounter() {
  context.dataStore.edit { settings ->
    val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
    settings[EXAMPLE_COUNTER] = currentCounterValue + 1
    // can we track success here? i am afraid code might execute asynchronously

  }

I'd like to track when it successfully writes to data store. Where should I put the tracking code?

Upvotes: 4

Views: 1096

Answers (1)

Michael Krause
Michael Krause

Reputation: 4849

The call to edit() is synchronous, so there is no need for a listener.

According to the Preferences DataStore edit documentation, there are three possible outcomes from calling edit():

  1. The transform block completes successfully and the data store successfully commits the changes to disk (no exception is thrown)
  2. An exception occurs during execution of your code in the transform block
  3. An IOException is thrown due to an error either reading or writing preference data from/to disk

Further, according to the Android developer codelab for preferences datastore:

All changes to MutablePreferences in the transform block will be applied to disk after transform completes and before edit completes.

So, I think wrapping the call to edit() in a try/catch block will do the trick.

Something like:

suspend fun incrementCounter() {
    try {
        context.dataStore.edit { settings ->
            val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
            settings[EXAMPLE_COUNTER] = currentCounterValue + 1
        }
        // If you got here, the preferences were successfully committed
    } catch (e: IOException) {
        // Handle error writing preferences to disk
    } catch (e: Exception) {
        // Handle error thrown while executing transform block
    }
}

Upvotes: 3

Related Questions