Somewhere in every mobile app is a small file holding what the user chose: dark mode, notification preferences, whether they finished onboarding. It is the least glamorous data the company holds and the first thing a customer notices when it is lost.
The Vendor Has Moved On
For over a decade Android apps wrote that file with one API. Google's own page for it now opens with a redirect: "DataStore is a modern data storage solution that you should use instead of SharedPreferences. It builds on Kotlin coroutines and Flow, and overcomes many of the drawbacks of SharedPreferences" (Android).
The weakness is visible in the old documentation itself. The fast way to save "changes the in-memory SharedPreferences object immediately but writes the updates to disk asynchronously", so the app is told the save worked before it has. The replacement stores data "asynchronously, consistently, and transactionally" (Android).
A Migration Is Not a One-Time Event
Existing customers have settings in the old file, so the move includes a migration. We had this wrong ourselves: our article said the migration runs exactly once. The contract says otherwise. "Methods on this migration (shouldMigrate, migrate and cleanUp) may be called multiple times, so their implementations must be idempotent" (Android). A migration written on the assumption that it runs once can apply itself twice.
The Rule That Shows Up in Crash Reports
The new tool is strict in ways the old one was not. "Never create more than one instance of DataStore for a given file in the same process. Doing so can break all DataStore functionality." It is also deliberately small: "DataStore is ideal for small datasets and does not support partial updates or referential integrity." It is a settings file, not a database.
What to Ask Your Team
- Are we still on the API the vendor tells us to leave?
- If we migrate, what happens if the migration runs twice?
- Is the migration tested against a file written by the shipped version?
- Is anything stored there that belongs in a database?
-Rocky
#TechnicalDebt #Android #DataStorage #EngineeringDreams #StrategiaX
Originally published on ANDROID-ARCHITECT, the Android engineering blog of Strategia-X, with the migration code.
