I am currently working with Android’s SharedPreferences to store a pair of key-value pairs.
(Let’s say “keyA-valueA” and “keyB-valueB”)
These pairs are always used together, therefore it is crucial that they are updated simultaneously. Here is the code snippet I will use:
val sharedPreferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("A", "valueA")
editor.putString("B", "valueB")
editor.apply()
My question is about the atomicity(transaction) of these updates. Specifically, I want to ensure that if one of the updates fails (for any reason), then both updates should fail. In other words, the changes should only be applied to disk if both updates succeed. Could you please confirm whether the above code guarantees this atomicity?
(I don’t want to save a instance having valueA, valueB because my app already saved two values separately so this method needs data migration.)