Reputation: 595
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
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()
:
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