Data Storage Best Practices with Jetpack
Article Summary
Florina Muntenescu and Rohit Sathyanarayana from Google reveal why SharedPreferences has been secretly blocking your UI thread and causing ANRs. Their solution? Jetpack DataStore, a complete reimagining of Android data storage.
The Android team introduces DataStore, a Kotlin coroutines and Flow-based replacement for SharedPreferences. The article breaks down two implementations (Proto and Preferences), compares them against legacy options, and provides migration guidance for existing apps.
Key Takeaways
- SharedPreferences blocks UI thread on fsync(), triggering ANRs at every service/activity lifecycle event
- Proto DataStore offers strongly typed schemas via Protocol Buffers with atomic transactions
- Built-in SharedPreferences migration runs automatically before any DataStore data access occurs
- All operations run on Dispatchers.IO with Flow-based async API eliminating UI blocking
DataStore replaces SharedPreferences with a fully asynchronous, type-safe storage solution that eliminates UI thread blocking and provides transactional data consistency.
About This Article
SharedPreferences can throw runtime exceptions when parsing fails, and there's no built-in error handling. The synchronous API also doesn't support transactions, which means data can get corrupted if multiple threads access it at the same time.
Google's DataStore team built a suspending updateData() function that handles read-write-modify operations as atomic transactions. Data gets written to disk before the coroutine finishes, so race conditions can't happen.
DataStore prevents parsing errors by using strongly typed Protocol Buffer schemas. Transactions guarantee that data stays consistent, and the Flow-based API runs all operations on Dispatchers.IO so the UI thread never gets blocked.